我目前的分组逻辑出错。我正在尝试对相同产品名称的 EMV 中的值求和。我在仅传递一些列表时遇到错误。如何避免此异常。我不知道在 linq experssion 中进行空检查
System.ArgumentNullException: 'Value cannot be null. Parameter name: key'
法典
public Dictionary<string, decimal> SumProductEmv(IEnumerable<FirmWideAllocationsViewModel> allProducts)
{
if (allProducts == null)
return null;
return allProducts
.GroupBy(product => product.ProductName)
.Select(group => new
{
ProductName = group.Key, // this is the value you grouped on - the ProductName
EmvSum = group.Sum(item => item.Emv)
})
.ToDictionary(x => x.ProductName, x => x.EmvSum);
}
您可以使用
Where
过滤掉null
或空键,请尝试以下操作:
return allProducts
.Where(product => !string.IsNullOrEmpty(product.ProductName))
.GroupBy(product => product.ProductName)
.Select(group => new
{
ProductName = group.Key, // this is the value you grouped on - the ProductName
EmvSum = group.Sum(item => item.Emv)
})
.ToDictionary(x => x.ProductName, x => x.EmvSum);
此外,您可以Distinct()
阻止 ArgumentException:字典中已经存在具有相同键的元素,但您需要决定要采用哪个元素,第一个,最后一个等。