System.ArgumentNullException:'值不能为null。参数名称:键

时间:2019-03-27 11:22:03

标签: c# linq

我目前在分组逻辑中遇到错误。我正在尝试对相同产品名称的EMV中的值求和。仅通过一些列表时出现错误。我如何避免这种异常。我不知道在linq expssion中执行空检查

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);
}

1 个答案:

答案 0 :(得分:6)

您可以过滤null或使用Where清空键,请尝试以下操作:

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:字典中已经存在具有相同键的元素,但随后您需要确定要采用的元素,首先,最后,等等。