简体   繁体   中英

System.ArgumentNullException: 'Value cannot be null. Parameter name: key'

I am currently getting error in my grouping logic. I am trying to sum the values in EMV for productnames that are same. I am getting error while passing only some list. How do I avoid this exception. I am not aware of doing null checks in linq experssion

System.ArgumentNullException: 'Value cannot be null. Parameter name: key'

Code

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

You could filter null or empty keys out using Where , try this:

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

Also, you could Distinct() to prevent ArgumentException: An element with the same key already exists in the dictionary but then you need to decide which element you want to take, first, last, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM