by paet the pagan-gerbil
25. March 2010 12:43
I’ve just found out how to combine .Sum() with a where clause, and all it took was a further step into the murky world of Linq.
I got my tip-off from a fellow BlogEngine.NET blog user Gary Kilminster - http://cunningplan.co.uk/post/Extension-Methods.aspx – although it doesn’t look like his blog has been updated for a while.
I had a list of custom objects, and wanted to get the sum of all their ‘Cost’ values as long as they had a specific property in common. The bit of Gary’s code that really made it click for me was:
string londonNames = (from c in db.Customers
where c.City == "London"
select c.CompanyName).Sum();
In my case, it became:
int result = (from o in objectList
where o.OptionGroupId == specificId
select o.Cost).Sum();
It’s just so simple and easy. Hooray!