Reputation: 11765
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:
----------------------------
Rate | Group
----------------------------
100 | A
120 | B
70 | A
----------------------------
I just wanna to get Sum A=170
an Sum B=120
.
Upvotes: 5
Views: 55710
Reputation: 4902
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]);
Upvotes: 4
Reputation: 94645
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()))
};
Upvotes: 14
Reputation: 6891
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 + "'");
Upvotes: 4