5

Possible Duplicate:
Find the most frequent numbers in an array using LINQ

I have a list of int, List<int> demoList, which is something like {1, 2, 1, 1, 1, 3, 2, 1} and I want to write a LINQ statement for obtaining the number with the highest number of appearences from that list, which in my case is 1.

Community
  • 1
  • 1
Simon
  • 4,999
  • 21
  • 69
  • 97

5 Answers5

7
var list = new[] { 1, 2, 1, 1, 1, 3, 2, 1 };
var result = list
    .GroupBy(x => x)
    .Select(x => new { Number = x.Key, Count = x.Count() })
    .OrderByDescending(x => x.Count)
    .FirstOrDefault();
Console.WriteLine("highest number = {0}, count = {1}", result.Number, result.Count);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
7
 int highestAppearanceNum = demoList.GroupBy(i => i)
            .OrderByDescending(grp => grp.Count())
            .Select(grp => grp.First())
            .First();

Edit: If you also want to know which number appears how often:

var appearances = demoList.GroupBy(i => i)
    .OrderByDescending(grp => grp.Count())
    .Select(grp => new { Num = grp.Key, Count = grp.Count() });
if (appearances.Any())
{
    int highestAppearanceNum = appearances.First().Num;     // 1
    int highestAppearanceCount = appearances.First().Count; // 5
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

Use group by clause.

var groups = 
    from i in demoList
    group i by i into g
    select new { Value = g.Key, Count = g.Count() }

From here you can say

var max = groups.Max(g => g.Count);
groups.Where(g => g.Count == max).Select (g => g.Value); // { 1 }
mellamokb
  • 56,094
  • 12
  • 110
  • 136
1
var query =
    from i in demoList
    group i by i into g
    orderby g.Count() descending
    select new { Value = g.Key, Count = g.Count() };

var result = query.First();
Console.WriteLine(
    "The number with the most occurrences is {0}, which appears {1} times",
    result.Value,
    result.Count);
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
0

I appologise in advance:

        List<int> demoList = new List<int>() { 1, 2, 1, 1, 1, 3, 2, 1 };

        Dictionary<int,int> keyOrdered = demoList.GroupBy(i => i)
            .Select(i => new { i.Key, Count = i.Count() })
            .OrderBy(i=>i.Key)
            .ToDictionary(i=>i.Key, i=>i.Count);

        var max = keyOrdered.OrderByDescending(i=>i.Value).FirstOrDefault();

        List<string> histogram = new List<string>();

        for (int i = max.Value; i >-1 ; i--)
        {
            histogram.Add(string.Concat(keyOrdered.Select(t => t.Value>i?"| ":"  ")));
        }

        histogram.Add(string.Concat(keyOrdered.Keys.OrderBy(i => i).Select(i => i.ToString() + " ")));

        histogram.ForEach(i => Console.WriteLine(i));

        Console.WriteLine(Environment.NewLine);
        Console.WriteLine("Max: {0}, Count:{1}", max.Key, max.Value);

when i read the title i thought of this and it made me smile.. (prolly full of bugs too!)