ssl
ssl

Reputation:

how would i use linq to find the most occured data in a data set?

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

//output
11

Upvotes: 2

Views: 162

Answers (3)

&#199;ağdaş Tekin
&#199;ağdaş Tekin

Reputation: 16651

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;

Upvotes: 0

Daniel Br&#252;ckner
Daniel Br&#252;ckner

Reputation: 59675

a.GroupBy(item => item).
  Select(group => new { Key = group.Key, Count = group.Count() }).
  OrderByDescending(pair => pair.Count).
  First().
  Key;

Upvotes: 2

JaredPar
JaredPar

Reputation: 755141

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;

}

Upvotes: 4

Related Questions