I have a DataSet with several rows and columns (as DataSets tend to have). I need to create a tally row on the bottom with sums of each column. I’d like to do this with a single LINQ expression, as it will simplify a bunch of my code. I can get the total of a single column like so:
var a = (from m in month
where <some long expression>
select m["BGCO_MINUTES"] as Decimal?).Sum();
However, I want totals for other columns as well. I don’t want to use multiple LINQ expressions because there’s also a complicated where clause in there, and I’m doing several tally rows with various expressions and only want to loop through this set once. I also don’t want to manually loop through the dataset myself and add up the totals since I’m creating many of these tally rows and think it would be messier.
What I want is an anonymous type that contains a total of BGCO_MINUTES, 800IB_MINUTES and TSDATA_MINUTES.
Is there any way to do this?
You could do this:
And that’s assuming your where clause is not just long to type, but computationally expensive to evaluate. That will iterate through the list once per column.
If you really want to only iterate the list once, you can probably do it with Enumerable.Aggregate, but the code is less elegant (in my opinion):
Like I said, I think it’s less elegant than the first version, but it should work. Even though the first one requires a temporary copy of the values that match the where clause (memory cost) and 1 pass through the list for each field (CPU cost), I think it’s a lot more readable than the latter version – make sure the performance difference is worth it before using the less-understandable version.