Search code examples
c#linq

How get max count with min key from list integer with linq written in one expression


For example I have following list

var arr = new List<int> { 1, 4, 4, 4, 5, 3 };

I implemented as:

var res1 = from type in arr
   group type by type into ByrdTypes
   select new
   {
      Group = ByrdTypes.Key,
      Count = ByrdTypes.Count()
   }; 


var correct = from item in res1
   where item.Count == res1.Max(y => y.Count)
   select item;

var result = correct.Min(x => x.Group);

This is working solution. But how can I rewrite this in one Linq expression(query)? Thank you.


Solution

  • You could just use OrderBy or OrderByDescending then First or Last

    var list = new List<int>() { 1, 4, 4, 4, 5, 3 };
    var result = list
       .GroupBy(type => type)
       .Select(x => new {Group = x.Key, Count = x.Count()})
       .OrderByDescending(x => x.Count)
       .First();
    
    // The above will get you the group with the highest count 
    
    Console.WriteLine(result);
    

    Output

    { Group = 4, Count = 3 }