简体   繁体   English

转换列表 <int> 到字典 <int,int> 使用LINQ

[英]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? 如何将列表转换为字典,其中值是使用LINQ列表中每个不同数字的计数? For example, the above list should be converted to a dictionary with the elements: 例如,上面的列表应该转换为包含以下元素的字典:

key -> value 关键 - >价值

5 -> 2 5 - > 2

6 -> 3 6 - > 3

7 -> 4 7 - > 4

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

Efficent solution (only 1 iteration over collection): Efficent解决方案(仅收集1次迭代):

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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