按DataTable列分组 [英] Group by in DataTable Column sum

查看:745
本文介绍了按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]);

这篇关于按DataTable列分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆