Tom
Tom

Reputation: 8681

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

Upvotes: 2

Views: 7896

Answers (1)

Johnny
Johnny

Reputation: 9509

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.

Upvotes: 7

Related Questions