查询和聚合数据表的问题 [英] Problem with quering and aggregation of DataTable
问题描述
我对LINQ相对较新,我正在尝试查询DataTable并计算其中的2列之和,然后将结果按其余字段分组.问题是我只能获取聚合的列值,而不能获取非聚合的值.这是我正在使用的代码:
I am relatively new to LINQ and I am trying to query a DataTable and calculating sum of 2 columns in it and grouping the result by the rest of the fields. The thing is I can only get the aggregated column values and I can''t get the non aggregated values. Here''s the code I am using:
var balances = from b in dtAccounts.AsEnumerable()<br /> group b by b.Field<decimal>("ACCOUNT_ID") into g<br /> select new { credit = g.Sum(b => b.Field<decimal>("CREDIT")), debit = g.Sum(b => b.Field<decimal>("DEBIT")) };
有人可以给他一些提示,我只是选择由account_id分组的借方和贷方字段之和;问题是我不知道如何选择带有汇总结果的account_id列.
Can someone give a hint about his piece of code, I simply select sums of the fields debit and credit grouped by account_id; the problem is I don''t know how to select account_id column with the aggregated results.
推荐答案
范围变量g具有一个属性Key,该属性表示分组的关键字.在您的情况下,这是b.Field< decimal>("ACCOUNT_ID").因此,如果您想获得带有结果的account_id,则需要以下查询:
The range variable g has a property Key that represents the key that you have grouped by. In your case, this is b.Field<decimal>("ACCOUNT_ID"). So, if you want to have the account_id with the results, you need this query:
var balances = from b in dtAccounts.AsEnumerable()<br /> group b by b.Field<decimal>("ACCOUNT_ID") into g<br /> select new<br /> {<br /> accountId = g.Key,<br /> credit = g.Sum(b => b.Field<decimal>("CREDIT")),<br /> debit = g.Sum(b => b.Field<decimal>("DEBIT"))<br /> }
希望这对您有所帮助
投票给我:)
Hope this helps
Vote me :)
这篇关于查询和聚合数据表的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!