1

我目前在分组逻辑中遇到错误。我正在尝试将 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);
}
4

1 回答 1

7

您可以使用 过滤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: An element with the same key has been exists in the dictionary but then you need to determine which element you want to take, first, last 等。

于 2019-03-27T11:26:26.457 回答