Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the most common value in an Int array? (C#)

Tags:

arrays

c#

int

How to get the most common value in an Int array using C#

eg: Array has the following values: 1, 1, 1, 2

Ans should be 1

like image 940
mouthpiec Avatar asked Apr 16 '10 19:04

mouthpiec


1 Answers

var query = (from item in array
        group item by item into g
        orderby g.Count() descending
        select new { Item = g.Key, Count = g.Count() }).First();

For just the value and not the count, you can do

var query = (from item in array
                group item by item into g
                orderby g.Count() descending
                select g.Key).First();

Lambda version on the second:

var query = array.GroupBy(item => item).OrderByDescending(g => g.Count()).Select(g => g.Key).First();
like image 97
Anthony Pegram Avatar answered Oct 19 '22 14:10

Anthony Pegram