List<int> a = 11,2,3,11,3,22,9,2
//output
11
views:
109answers:
3
+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
2009-04-03 03:24:19
Nice! Almost bitidentical... :D
Daniel Brückner
2009-04-03 03:35:44
@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
2009-04-03 03:39:17
+2
A:
a.GroupBy(item => item).
Select(group => new { Key = group.Key, Count = group.Count() }).
OrderByDescending(pair => pair.Count).
First().
Key;
Daniel Brückner
2009-04-03 03:34:44
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ş
2009-04-03 04:27:08