I’m trying to provide to a DataGridview (winform) a one statement query in LINQ.
The following line assign the sum of records values either to Debt or Credit member depending of the sum.
transaction 1—* record
var transactions = from t in this.account.transactions select new {
Debt = t.records.Sum(x=>x.value) < 0 ? t.records.Sum(x=>x.value).ToString() : String.Empty,
Credit = t.records.Sum(x => x.value) > 0 ? t.records.Sum(x => x.value).ToString() : String.Empty
};
But I’m facing two issues, these can be quite easily solved, but I’m searching for something clean and efficient.
-
How preventing calling the Sum method so many time ? any idea for re-factoring and reduce the amount of call ?
-
I would like to add a new member called Balance which basically sum the previous balance sum (in the previous iteration) with the current one. Is it possible (and clean) to do it directly in the new statement ? using a delegate ?
Regards
Regarding your first question, here’s how you could do it:
As for your second question, I’d really be interested in a clean solution as well. LINQ does not seem to be designed to work on anything other than a single record. You could do
but I would not call this “clean”. =)