按DataTable列分组
问题描述:
在以下代码中,在 DataTable dt
dt.Compute("Sum(Convert(Rate, 'System.Int32'))");
在这里可以分配 group by子句,如SQL
Inn订单根据相同 dt的另一列中的值获得总和
Fo eg:
In this is it possible to assign group by clause like SQL
Inn order to get Sum based on a value in another column of the same dt
Fo eg:
----------------------------
Rate | Group
----------------------------
100 | A
120 | B
70 | A
----------------------------
我只想获得 Sum A = 170
a Sum B = 120
。
答
使用LINQ是个好主意。如果您正在使用.net 2.0,您可以执行如下:
using LINQ is a good idea. if you are working with .net 2.0, you can implement this as follows:
Dictionary<string, int> dicSum = new Dictionary<string, int>();
foreach (DataRow row in dt.Rows)
{
string group=row["Group"].ToString();
int rate=Convert.ToInt32(row["Rate"]);
if (dicSum.ContainsKey(group))
dicSum[group] += rate;
else
dicSum.Add(group, rate);
}
foreach (string g in dicSum.Keys)
Console.WriteLine("SUM({0})={1}", g, dicSum[g]);