gpt4 book ai didi

c# - 使用 LINQ 将 List 转换为 Dictionary

转载 作者:太空狗 更新时间:2023-10-30 00:04:52 26 4
gpt4 key购买 nike

假设我有以下列表:

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

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

键 -> 值

5 -> 2

6 -> 3

7 -> 4

最佳答案

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

关于c# - 使用 LINQ 将 List<int> 转换为 Dictionary<int,int>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25844294/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com