c# - Single LINQ expression to tally up several columns in a DataSet -
i have dataset
several rows , columns (as datasets tend have). need create tally row on bottom sums of each column. i'd single linq expression, simplify bunch of code. can total of single column so:
var = (from m in month <some long expression> select m["bgco_minutes"] decimal?).sum();
however, want totals other columns well. don't want use multiple linq expressions because there's complicated where clause in there, , i'm doing several tally rows various expressions , want loop through set once. don't want manually loop through dataset myself , add totals since i'm creating many of these tally rows , think messier.
what want anonymous type contains total of bgco_minutes
, 800ib_minutes
, tsdata_minutes
.
is there way this?
you this:
// run filters once , list<datarow> matching rows var list = (from m in month <some long expression> select m).tolist(); // build summary object var result = new { bgco_minutes = list.sum(m => m["bgco_minutes"] decimal?), _800ib_minutes= list.sum(m => m["800ib_minutes"] decimal?), }
and that's assuming clause not long type, computationally expensive evaluate. will iterate through list once per column.
if want iterate list once, can enumerable.aggregate, code less elegant (in opinion):
// run filters once , list<datarow> matching rows var = (from m in month <some long expression> select m) .aggregate( new { bgco_minutes = (decimal?)0m, _800ib_minutes = (decimal?)0m }, (ac,v) => new { bgco_minutes = ac.bgco_minutes + (decimal?)v["bgco_minutes"], _800ib_minutes = ac._800ib_minutes + (decimal?)v["800ib_minutes"] });
like said, think it's less elegant first version, should work. though first 1 requires temporary copy of values match clause (memory cost) , 1 pass through list each field (cpu cost), think it's lot more readable latter version - make sure performance difference worth before using less-understandable version.
Comments
Post a Comment