C# 将列表转换为字典并使用linq求和值
我有列表,即C# 将列表转换为字典并使用linq求和值,c#,linq,C#,Linq,我有列表,即列表。这个字段类包含一个代码和一个值属性以及其他字段,我希望能够使用linq来汇总同一代码的所有值 我知道我可以循环浏览我的列表,并使用以下代码将其添加到字典中,但我确信必须有一种更干净的方法来实现这一点: if (totals.ContainsKey(code)) { totals[code] += value; } else { totals.Add(code, value); } if (totals.ContainsKey(code)) { totals[cod
列表
。这个字段类包含一个代码和一个值属性以及其他字段,我希望能够使用linq来汇总同一代码的所有值
我知道我可以循环浏览我的列表,并使用以下代码将其添加到字典中,但我确信必须有一种更干净的方法来实现这一点:
if (totals.ContainsKey(code))
{
totals[code] += value;
}
else
{
totals.Add(code, value);
}
if (totals.ContainsKey(code))
{
totals[code] += value;
}
else
{
totals.Add(code, value);
}
有什么想法吗
我发现了类似的东西,但这适用于列表>,而我没有:
var result = Sales.SelectMany(d => d) // Flatten the list of dictionaries
.GroupBy(kvp => kvp.Key, kvp => kvp.Value) // Group the products
.ToDictionary(g => g.Key, g => g.Sum());
var result = Sales.SelectMany(d => d) // Flatten the list of dictionaries
.GroupBy(kvp => kvp.Key, kvp => kvp.Value) // Group the products
.ToDictionary(g => g.Key, g => g.Sum());
从这篇文章中[Sum amount using Linq in这不是我所拥有的:
var result = Sales.SelectMany(d => d) // Flatten the list of dictionaries
.GroupBy(kvp => kvp.Key, kvp => kvp.Value) // Group the products
.ToDictionary(g => g.Key, g => g.Sum());
var result = Sales.SelectMany(d => d) // Flatten the list of dictionaries
.GroupBy(kvp => kvp.Key, kvp => kvp.Value) // Group the products
.ToDictionary(g => g.Key, g => g.Sum());
从这篇文章中[Sum amount using Linq in实际上没有什么不同,因为我当时实际上想总结一个列表,所以提供的答案是正确的!谢谢!您发布的代码几乎就是您所需要的-对于在列表中使用它,您需要稍微简化一下:
var result = myList // No flattening
.GroupBy(x => x.Code) // Group the items by the Code
.ToDictionary(g => g.Key, g => g.Sum(v => v.Value)); // Total up the values
var list=新列表
{
新字段{Code=“A”,值=10},
新字段{Code=“A”,值=20},
新字段{Code=“B”,值=30},
};
var dic=列表
.GroupBy(z=>z.Code)
.ToDictionary(z=>z.Key,z=>z.Sum(f=>f.Value));
您可以执行以下操作:
Dictionary<string, int> dictionary =
list.GroupBy(r => r.ID)
.ToDictionary(grp => grp.Key, grp => grp.Sum(r => r.Value));
我认为组Sum
是必需的。@Habib你是对的,Sum
确实是必需的(现在已修复)。