(转)C#用Linq实现DataTable的Group by数据统计

本文转载自:http://www.cnblogs.com/sydeveloper/archive/2013/03/29/2988669.html

1、用两层循环计算,前提条件是数据已经按分组的列排好序的。

DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("name", typeof(string)),
                                        new DataColumn("sex", typeof(string)),
                                        new DataColumn("score", typeof(int)) });
dt.Rows.Add(new object[] { "张三","男",1 });
dt.Rows.Add(new object[] { "张三","男",4 });
dt.Rows.Add(new object[] { "李四","男",100 });
dt.Rows.Add(new object[] { "李四","女",90 });
dt.Rows.Add(new object[] { "王五","女",77 });
DataTable dtResult = dt.Clone();
for (int i = 0; i < dt.Rows.Count; )
{
    DataRow dr = dtResult.NewRow();
    string name = dt.Rows[i]["name"].ToString();
    string sex = dt.Rows[i]["sex"].ToString();
    dr["name"] = name;
    dr["sex"] = sex;
    int score = 0;
    //内层也是循环同一个表,当遇到不同的name时跳出内层循环
    for (; i < dt.Rows.Count; )
    {
        if (name == dt.Rows[i]["name"].ToString()&&name == dt.Rows[i]["sex"].ToString())
        {
            score += Convert.ToInt32(dt.Rows[i]["score"]);
            dr["score"] = score;
            i++;
        }
        else
        {
            break;
        }
    }
    dtResult.Rows.Add(dr);
}

dtResult中的数据即是最终结果。

2、 借助DataTable的Compute方法,DataTable中数据不用事先排好序。

DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("name", typeof(string)),
                                         new DataColumn("sex", typeof(string)),
                                         new DataColumn("score", typeof(int)) });
dt.Rows.Add(new object[] { "张三","男",1 });
dt.Rows.Add(new object[] { "张三","男",4 });
dt.Rows.Add(new object[] { "李四","男",100 });
dt.Rows.Add(new object[] { "李四","女",90 });
dt.Rows.Add(new object[] { "王五","女",77 });
DataTable dtResult = dt.Clone();
DataTable dtName = dt.DefaultView.ToTable(true, "name","sex");
for (int i = 0; i < dtName.Rows.Count; i++)
{
    DataRow[] rows = dt.Select("name=‘" + dtName.Rows[i][0] + "‘ and sex=‘" + dtName.Rows[i][1] + "‘");
    //temp用来存储筛选出来的数据
    DataTable temp = dtResult.Clone();
    foreach (DataRow row in rows)
    {
        temp.Rows.Add(row.ItemArray);
    }

    DataRow dr = dtResult.NewRow();
    dr[0] = dtName.Rows[i][0].ToString();
    dr[1] = temp.Compute("sum(score)", "");
    dtResult.Rows.Add(dr);
} 

3、使用linq to DataTable group by实现

var query = from t in dt.AsEnumerable()
            group t by new { t1 = t.Field<string>("name"), t2 = t.Field<string>("sex") } into m
            select new
            {
                name = m.Key.t1,
                sex = m.Key.t2,
                score = m.Sum(n => n.Field<decimal>("score"))
            };
if (query.ToList().Count > 0)
{
    query.ToList().ForEach(q =>
    {
        Console.WriteLine(q.name + "," + q.sex + "," + q.score);
    });
} 
时间: 2024-10-11 02:43:33

(转)C#用Linq实现DataTable的Group by数据统计的相关文章

C#用DataTable实现Group by数据统计

1.用两层循环计算,前提条件是数据已经按分组的列排好序的. DataTable dt = new DataTable();dt.Columns.AddRange(new DataColumn[] { new DataColumn("name", typeof(string)),                                        new DataColumn("sex", typeof(string)),                 

linq to datatable 和lambda查询datatable

用Linq查询DataTable static DataTable table = new DataTable(); static DataColumn dc = new DataColumn(); static void Main() { Createtable(); table.Rows.Add(1, 2,"2010-1-1"); table.Rows.Add(2, 3, "2010-1-1"); table.Rows.Add(3, 4, "2010-

Working with LINQ to Entities &amp; LINQ to DataTable

Introduction Now a days, working with LINQ is an added advantage for any developer. We can write almost all types of queries when compared with SQL Server SQL querying. The important thing in LINQ is understanding the syntax and what it returns. Back

Linq查询datatable的记录集合

通过linq查询datatable数据集合满足条件的数据集 1.首先定义查询字段的变量,比方深度 string strDepth=查询深度的值: var dataRows = from datarow in dataTable(须要查询的datatable数据集).AsEnumerable() where string.Compare(datarow.Field<string>("查询字段.比方深度字段"), strDepth) >= 100 && s

C# Linq to sql 实现 group by 统计多字段 返回多字段

Linq to sql 使用group by 统计多个字段,然后返回多个字段的值,话不多说,直接上例子: var wflist = from u in db.TWelFare where u.fy_no == fy_no orderby u.we_no group u by new { weno = u.we_no, wename = u.we_name } into g select new { g.Key.weno, g.Key.wename }; 结果就是根据we_no和we_name的统

C# Linq To DataTable 分组统计 DEMO

DataTable dt = SQLLayer.Get工作量统计(beginDate, endDate);            var querySum = from t in dt.AsEnumerable()                           group t by t.Field<string>("库房")                               into g                               selec

LINQ返回DataTable类型 list转dataset 转换为JSON对象

using System.Web.Script.Serialization; using System.Collections.Generic; using System.Reflection; using System.Data; using System; namespace CommonCode { public class Common { /// <summary> /// LINQ返回DataTable类型 /// </summary> public static Da

datatable使用groupby进行分组统计

1.用两层循环计算,前提条件是数据已经按分组的列排好序的. DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[] { new DataColumn("name", typeof(string)), new DataColumn("sex", typeof(string)), new DataColumn("score", typeof(int)) }); dt.R

C# DataTable 转换成JSON数据

原文:C# DataTable 转换成JSON数据 using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Web; using System.Web.Script.Serialization; namespace WsDemo { public class DataTableConvertJson { #region