使用LINQ将List <int>转换为Dictionary <int,int>

Set*_*o N 4 c# linq dictionary list

说我有以下列表:

  List<int> list = new List<int>() { 5, 5, 6, 6, 6, 7, 7, 7, 7 };
Run Code Online (Sandbox Code Playgroud)

如何将列表转换为字典,其中值是使用LINQ列表中每个不同数字的计数?例如,上面的列表应该转换为包含以下元素的字典:

关键 - >价值

5 - > 2

6 - > 3

7 - > 4

Ser*_*kiy 10

var result = list.GroupBy(i => i).ToDictionary(g => g.Key, g => g.Count());
Run Code Online (Sandbox Code Playgroud)