Group by in DataTable Column sum
In the following code for finding sum of Rate colum
n in the DataTable dt
dt.Compute("Sum(Convert(Rate, 'System.Int32'))");
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:
----------------------------
R开发者_运维问答ate | Group
----------------------------
100 | A
120 | B
70 | A
----------------------------
I just wanna to get Sum A=170
an Sum B=120
.
Try LINQ,
var result = from tab in dt.AsEnumerable()
group tab by tab["Group"]
into groupDt
select new
{
Group = groupDt.Key,
Sum=groupDt.Sum((r)=> decimal.Parse(r["Rate"].ToString()))
};
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]);
You might want to get the list of distinct Group values from the DataTable first. Then loop through the list of Groups and call the function for each Group:
dt.Compute("Sum(Convert(Rate, 'System.Int32'))", "Group = '" + Group + "'");
精彩评论