I have the following LINQ expression:
pantry = (from p in items
group p by p.IngredientId into g
select new PantryItem() { IngredientId = g.Key, Amt = g.Sum(p => p.Amt) });
Basically, I’m trying to remove duplicates from an array by summing up their total amounts. So if I have 2 items of IngredientId x, one with Amt 5 and the other with Amt 10, I want a single item of Ingredient x with the Amt 15. Easy enough right?
Now, to completely break everything, Amt is actually a float?, not a float. However, when I Sum a group with all null amounts, I get 0.0 instead of null.
Here’s what I want:
x - null
x - null
y - 5
y - 10
z - 10
z - null
Should convert to:
x - null
y - 15
z - 10
But instead I get:
x - 0.0
y - 15
z - 10
Is there a way to re-work my LINQ query to facilitate this? Hopefully my question is clear enough 🙂
You have 2 choices:
Sumnull, then returnnull, otherwise return sum, e.g.:NOTE: 2nd query will enumerate twice.