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

How can I use LINQ to find the number of the largest group of objects in a collection of objects?

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 does not work for me as it led to an error:

ArgumentException: at least one object must implement IComparable.

How can I fix this LINQ query (if it is incorrect) or what should I look for to prevent this error if it is correct?

+3
source share
1 answer

" ", . ; , Enumerable.Max , Count.

, , :

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

Max, " Int32".

:

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

, , .

+11

Source: https://habr.com/ru/post/1786041/


All Articles