LINQ DataTable Sum In Where Clause
I'm having a rough time figuring out exactly how to do a LINQ query on a DataTable and return a full row while having the WHERE clause test on a sum.
My code:
transactionsToRemove.AddRange(paymentTransactionResults
.AsEnumerable()
.Where(...)
.GroupBy(r => (decimal)r["AccountNumber"]));
There are multiple transactions for each AccountNumber, and I need to sum those together and determine whether they're less than a user inputted amount (For my purpose, it's called balanceGreaterThan). I can't find any examples to go by where someone has done this sort of thing.
Thanks in adva开发者_如何学编程nce, SO.
Edit: My apologies -- The column I need to sum is called "Balance"
Edit 2: Final code
transactionsToRemove.AddRange(paymentTransactionResults
.AsEnumerable()
.GroupBy(r => r.Field<string>("AccountNumber"))
.Where(g => g.Sum(r => r.Field<decimal>("Balance")) < balanceGreaterThan)
.SelectMany(g => g));
I had to change the GroupBy to use r.Field rather than r["AccountNumber"]
You're trying to filter the groups themselves (to find which groups have a large sum), not the rows that go into the groups.
Therefore, you need to put the Where()
call after the GroupBy
:
transactionsToRemove.AddRange(paymentTransactionResults
.AsEnumerable()
.GroupBy(r => (decimal)r["AccountNumber"])
.Where(g => g.Sum(r => r.Field<decimal>("Balance") < balanceGreaterThan));
EDIT: If you want to get an IEnumerable<DataRow>
back (as opposed to an IEnumerable<IGrouping<DataRow>>
), you'll need to add .SelectMany(g => g)
.
transactionsToRemove.AddRange(paymentTransactionResults
.AsEnumerable()
.GroupBy(r => (decimal)r["AccountNumber"])
.Where(g => g.Sum(r => (decimal)r["Balance"]) <= someInput)
.SelectMany(g => g));
I think you want something like:
transactionsToRemove.AddRange(paymentTransactionResults
.AsEnumerable()
.GroupBy(r => (decimal)r["AccountNumber"]));
.Where(grp => grp.Sum(r => r["amount"]) < balanceGreaterThan);
精彩评论