简体   繁体   中英

Convert List<int> to a Dictionary<int,int> using LINQ

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

var result = list.GroupBy(i => i).ToDictionary(g => g.Key, g => g.Count());

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;
    }
}
var group = list.GroupBy(T => T).ToDictionary(T => T.Key, T => T.Count())

try this:

var dic =    list.GroupBy(c => c)
                 .Select(c => new {c.Key, Count = c.Count()})
                 .ToDictonary(c => c.Key, q => q.Count)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM