好的,我有一个简单的IEnumerable<HtmlString> things
,我想将其分为四个相等的组。
var quarter = things.OrderBy(t => t.Foo).Count() / 4;
应该可以解决问题,但是我却变得很时髦:有人知道这里发生了什么吗?为什么我需要实现IComparable来进行简单计数?
最佳答案
我的猜测是,这与LINQ的OrderBy
的惰性求值有关。例如,如果您有:
var things = unsortedThings.OrderBy(foo => foo.Bar);
var quarter = things.Count() / 4;
那么如果无法将
foo.Bar
属性相互比较,则将抛出该异常。例如:
using System;
using System.Linq;
class Foo {}
class Program
{
public static void Main()
{
var foos = new[] { new Foo(), new Foo() };
var ordered = foos.OrderBy(x => x);
Console.WriteLine(ordered.Count());
}
}
输出:
Unhandled Exception: System.ArgumentException: At least one object must implement IComparable.
at System.Collections.Comparer.Compare(Object a, Object b)
at System.Linq.EnumerableSorter`2.CompareKeys(Int32 index1, Int32 index2)
at System.Linq.EnumerableSorter`1.QuickSort(Int32[] map, Int32 left, Int32 right)
at System.Linq.EnumerableSorter`1.Sort(TElement[] elements, Int32 count)
at System.Linq.OrderedEnumerable`1.<GetEnumerator>d__0.MoveNext()
at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source)
at Program.Main()
关于c# - int的"At least one object must implement IComparable"吗?据我所知,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12538150/