【问题标题】:System.ArgumentNullException: 'Value cannot be null. Parameter name: key'System.ArgumentNullException: '值不能为空。参数名称:key'
【发布时间】:2019-08-17 22:46:02
【问题描述】:

我目前的分组逻辑出现错误。我正在尝试将 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);
}

【问题讨论】:

  • 大概ProductName 为空。我想在 group by 解决这个问题之前有一个.Where

标签: c# linq


【解决方案1】:

您可以使用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:字典中已经存在具有相同键的元素,但是你需要决定你想取哪个元素,首先,最后等等.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-03
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    相关资源
    最近更新 更多