-
Notifications
You must be signed in to change notification settings - Fork 4.9k
Description
The below code fails with this exception:
System.ArgumentException: At least one object must implement IComparable.
However, if you change this line...
calendarDurations.Add(30);
... to use this...
calendarDurations.Add(14);
... it works.
So it appears the order, or a specfic number matters. This was done on dotnetfiddle.net with .NET 4.7.2 and .NET 6.
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var calendarDurations = new List<double>();
calendarDurations.Add(14);
calendarDurations.Add(14);
calendarDurations.Add(30);
calendarDurations.Add(30);
calendarDurations.Add(7);
// Get the duration that appears most often. If a tie, take the higher number.
var max = calendarDurations
.GroupBy(x => x)
.Select(x => new { num = x, count = x.Count() })
.OrderByDescending(g => g.count)
.ThenByDescending(g => g.num)
.Select(g => g.num)
.First();
int calendaryDuration = (int)max.Key;
Console.WriteLine(calendaryDuration);
}
}
Stack trace:
Unhandled exception. System.ArgumentException: At least one object must implement IComparable.
at System.Collections.Comparer.Compare(Object a, Object b)
at System.Collections.Generic.ObjectComparer1.Compare(T x, T y) at System.Linq.CachingComparer2.Compare(TElement element, Boolean cacheLower)
at System.Linq.CachingComparerWithChild2.Compare(TElement element, Boolean cacheLower) at System.Linq.OrderedEnumerable1.TryGetFirst(Boolean& found)
at System.Linq.Enumerable.SelectIPartitionIterator2.TryGetFirst(Boolean& found) at System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable1 source, Boolean& found)
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at Program.Main()
Command terminated by signal 6