开发者

How do I use LINQ to count number of objects in largest group?

How can I use LINQ to find the count of the largest group of objects in an object collection?

As an example:

struct MyObject
{
    public int SomeInt;
    public int GroupInt;
}

List<MyObject> ObjectList = new List<MyOBject>();

// populate list

int LargestGroup = ObjectList.GroupBy(x => x.GroupInt).Max().Count();

This doesn't seem to work for me, as it resulted in an error:

ArgumentException: At least one object must implement IComparable.

How can I correct this LINQ query (if it is wrong) or what should I look fo开发者_开发百科r to prevent this error if it is correct?


Your current query is trying to find the 'maximum group' and then subsequently retrieving that group's count. This clearly doesn't make sense; groups don't have any natural order, and there's no way for Enumerable.Max to know that you're interested in finding the group with the biggest Count.

What you probably want is:

int largestGroupCount = ObjectList.GroupBy(x => x.GroupInt)
                                  .Max(g => g.Count());

which uses the overload of Max that "Invokes a transform function on each element of a sequence and returns the maximum Int32 value."

One could view this as similar to:

int largestGroupCount = ObjectList.GroupBy(x => x.GroupInt)
                                  .Select(g => g.Count()) 
                                  .Max();

which creates a sequence by projecting each group to its count, and then finds the maximum of that sequence.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜