4

Say I have the following list:

  List<int> list = new List<int>() { 5, 5, 6, 6, 6, 7, 7, 7, 7 };

How could I convert the list to a Dictionary where the value is the count of each distinct number in the list by using LINQ? For example, the above list should be converted to a dictionary with the elements:

key -> value

5 -> 2

6 -> 3

7 -> 4

Setyo N
  • 1,953
  • 2
  • 26
  • 28
  • I was going to close this as a duplicate of [this](http://stackoverflow.com/questions/687313/building-a-dictionary-of-counts-of-items-in-a-list) but the answers here are already better than those. (Maybe we should close and provide better answers there but it's always easier just to provide one line of code and get some rep.) – Rawling Sep 15 '14 at 09:06
  • Are values always grouped by it's value like in your example? –  Sep 15 '14 at 09:21
  • @pwas: the values are not always grouped but it is easy to sort the list. – Setyo N Sep 15 '14 at 09:56

4 Answers4

10
var result = list.GroupBy(i => i).ToDictionary(g => g.Key, g => g.Count());
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
2

Efficent solution (only 1 iteration over collection):

var output = new Dictionary<int, int>();
foreach (var val in list)
{
    if (!output.ContainsKey(val)) 
    {
        output.Add(val, 1);
    }
    else
    {
        output[val] = output[val] + 1;
    }
}
1
var group = list.GroupBy(T => T).ToDictionary(T => T.Key, T => T.Count())
AgentFire
  • 8,944
  • 8
  • 43
  • 90
1

try this:

var dic =    list.GroupBy(c => c)
                 .Select(c => new {c.Key, Count = c.Count()})
                 .ToDictonary(c => c.Key, q => q.Count)
Jens Kloster
  • 11,099
  • 5
  • 40
  • 54