tags:

views:

109

answers:

3
List<int> a = 11,2,3,11,3,22,9,2

//output
11
+4  A: 

This may not be the most efficient way, but it will get the job done.

public static int MostFrequent(IEnumerable<int> enumerable)
{
    var query = from it in enumerable
                 group it by it into g
                 select new {Key = g.Key, Count = g.Count()} ;
   return query.OrderByDescending(x => x.Count).First().Key;
}

And the fun single line version ...

public static int MostFrequent(IEnumerable<int> enumerable)
{
    return (from it in enumerable
                 group it by it into g
                 select new {Key = g.Key, Count = g.Count()}).OrderByDescending(x => x.Count).First().Key;

}
JaredPar
Nice! Almost bitidentical... :D
Daniel Brückner
@danbruc, yes. I usually prefer the expanded LINQ syntax (your answer) but GroupBy trips me up for some reason even though it's much easier in expanded syntax (IMHO).
JaredPar
+2  A: 
a.GroupBy(item => item).
  Select(group => new { Key = group.Key, Count = group.Count() }).
  OrderByDescending(pair => pair.Count).
  First().
  Key;
Daniel Brückner
A: 

Another example :

IEnumerable<int> numbers = new[] { 11, 2, 3, 11, 3, 22, 9, 2 };
int most = numbers
    .Select(x => new { Number = x, Count = numbers.Count(y => y == x) })
    .OrderByDescending(z => z.Count)
    .First().Number;
çağdaş