Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by in DataTable Column sum

In the following code for finding sum of Rate column 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.

like image 299
Nithesh Narayanan Avatar asked Oct 12 '11 07:10

Nithesh Narayanan


3 Answers

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()))
                  };
like image 55
KV Prajapati Avatar answered Nov 14 '22 08:11

KV Prajapati


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]);
like image 4
ojlovecd Avatar answered Nov 14 '22 08:11

ojlovecd


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 + "'");
like image 3
Fun Mun Pieng Avatar answered Nov 14 '22 09:11

Fun Mun Pieng