gpt4 book ai didi

C# 循环遍历字典并对键的值求和

转载 作者:行者123 更新时间:2023-11-30 21:49:42 25 4
gpt4 key购买 nike

我有一个 Dictionary<string, decimal?> ,我希望能够通过不同的字符串对小数求和。所以说我在字典中有以下输入,

“1”, 20.00“1”,35.00“2”,10.00"3", 15.00"3", 30.00

我想将以下输出到新词典

“1”, 55.00“2”,10.00"3", 45.00

我猜应该是这样的

foreach(var item in dictionary)
{
newDictionary.Add(not sure what would go here, maybe some sort of linq query for distinct and sum?);
}

最佳答案

假设键值对列表与其他答案相同:

var myList = New List<KeyValuePair<string, decimal?>> {
new KeyValuePair<string, decimal?>("1", (decimal)10.00),
new KeyValuePair<string, decimal?>("1", (decimal)15.00),
new KeyValuePair<string, decimal?>("2", (decimal)20.00),
new KeyValuePair<string, decimal?>("3", (decimal)30.50),
new KeyValuePair<string, decimal?>("3", (decimal)17.500)
};

var myResults = myList.GroupBy(p => p.Key)
.ToDictionary(g => g.Key, g=>g.Sum(p=>p.Value))

关于C# 循环遍历字典并对键的值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36778497/

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