Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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 for to prevent this error if it is correct?

like image 206
JYelton Avatar asked Jan 18 '11 01:01

JYelton


1 Answers

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.

like image 85
Ani Avatar answered Oct 02 '22 04:10

Ani