按DataTable Column sum中的两列分组
本文关键字:两列 Column DataTable sum | 更新日期: 2023-09-27 18:12:34
在以下代码中查找DataTable中Rate列的和:
dt.Compute("Sum(Convert(Rate, 'System.Int32'))");
在这种情况下,可以分配group by子句,如SQL Inn,以便根据相同dt的另一列中的值获得Sum。例如:
----------------------------
Rate | Group |type
----------------------------
100 | A | 1
120 | B | 2
70 | A | 1
50 | A | 2
----------------------------
我只想得到。
Sum A=170(type-1) SUMA=50(type-2) an Sum B=120(type-2)
Ref:在单列情况下,我在前面的问题中得到了ans
您可以按匿名类型分组:
var result = from r in dt.AsEnumerable()
group r by new { Group = r["Group"], Type = r["Type"] } into g
select new { Group = g.Key.Group,
Type = g.Key.Type,
Sum = g.Sum(x => Convert.ToInt32(x["Rate"])) };
foreach (var r in result)
{
Console.WriteLine("Group {0}, Type {1}, Sum {2}", r.Group, r.Type, r.Sum);
}