我有以下LINQ查询:
var groupedData = from b in loans.AsEnumerable()
group b by b.Field<int>("loan_code") & b.Field<int>("emp_num")
into f
select f.CopyToDataTable();
我想选择f
,除了Tot
字段的总和,并将结果复制到数据表中。如何做?
答案 0 :(得分:1)
获取所需数据
var groupedData = from r in loans.AsEnumerable()
group r by new {
LoanCode = r.Field<int>("loan_code"),
EmpNum = r.Field<int>("emp_num")
} into g
select new {
g.Key.LoanCode,
g.Key.EmpNum,
Tot = g.Sum(r => r.Field<int>("Tot")) // assume integer
};
然后使用自定义CopyToDataTable方法(适用于不实现DataRow的类型)将它们转换为DataTable。或者您可以手动构建DataTable:
DataTable dt = new DataTable();
dt.Columns.Add("loan_code", typeof(int));
dt.Columns.Add("emp_num", typeof(int));
dt.Columns.Add("Tot", typeof(int));
foreach(var data in groupedData)
dt.Rows.Add(data.LoanCode, data.EmpNum, data.Tot);