C# 如何对DataTable执行group by 操作呢?


摘要:
下文讲述c#中对DataTable执行group by聚合操作的方法分享,如下所示;

 实现思路:  
     借助linq对DataTable实现group by  

例:
DataTable group by示例分享

  using System;

using System.Data;
using System.Linq;
namespace consoleTest
{ 
    class Program
    {
        static void Main(string[] args)
        { 
            Console.WriteLine("www.maomao365.com cSharp示例分析:");

            //初始化数据表
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[] { new DataColumn("info", typeof(string)),
                                        new DataColumn("sort", typeof(string)),
                                        new DataColumn("qty", typeof(int)) });
            dt.Rows.Add(new object[] { "猫猫教程", "A", 88 });
            dt.Rows.Add(new object[] { "maomao365.com", "A", 98 });
            dt.Rows.Add(new object[] { "maomao365.com", "A", 87 });
            dt.Rows.Add(new object[] { "maomao365.com", "B", 60 });
            dt.Rows.Add(new object[] { "猫猫教程", "B", 99 });

            //对数据表dt按照info sort列执行,group by,并求和qty 

            var q = from t in dt.AsEnumerable()
                        group t by new { t1 = t.Field("info"), t2 = t.Field("sort") } into m
                        select new
                        {
                            info = m.Key.t1,
                            sort = m.Key.t2,
                            qtySum = m.Sum(n => n.Field("qty"))
                        };

            //输出group by 后的测试数据
            if (q.ToList().Count > 0)
            {
                q.ToList().ForEach(t =>
                {
                    Console.WriteLine(t.info + "," + t.sort + "," + t.qtySum);
                });
            }


            Console.ReadLine();
        }

 
    }
}
c#对DataTable执行group by示例分享

c#对DataTable执行group by示例分享