DataTable实现分组

有时候我们从数据库中查询出来数据之后,需要按照DataTable的某列进行分组,可以使用下面的方法实现,代码如下:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataTableGroupDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 准备数据
            DataTable dt = new DataTable();
            // 创建列
            DataColumn dcName = new DataColumn("Name", typeof(string));
            DataColumn dcAge = new DataColumn("Age", typeof(Int32));
            DataColumn dcScore = new DataColumn("Score", typeof(Int32));
            // 添加列
            dt.Columns.Add(dcName);
            dt.Columns.Add(dcAge);
            dt.Columns.Add(dcScore);
            // 添加数据
            dt.Rows.Add(new object[] { "Tom", 23, 67 });
            dt.Rows.Add(new object[] { "Tom", 23, 67 });
            dt.Rows.Add(new object[] { "Jack", 21, 100 });
            dt.Rows.Add(new object[] { "Greey", 24, 56 });
            dt.Rows.Add(new object[] { "Kevin", 24, 77 });
            dt.Rows.Add(new object[] { "Tom", 23, 82 });
            dt.Rows.Add(new object[] { "Greey", 24, 80 });
            dt.Rows.Add(new object[] { "Jack", 21, 90 });


            #region 使用Linq expression to DataTable group by
            var query = from p in dt.AsEnumerable()
                        group p by new { name = p.Field<string>("Name"),score=p.Field<Int32>("Score") } into m
                        select new
                        {
                            Name = m.Key.name,
                            Score=m.Key.score
                        };
            #endregion

            // 输出
            Console.WriteLine("Linq");
            foreach (var item in query)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("GroupBy");
            IEnumerable<IGrouping<string, DataRow>> result = dt.Rows.Cast<DataRow>().GroupBy<DataRow, string>(dr => dr["Name"].ToString());
            foreach (IGrouping<string, DataRow> ig in result)
            {
                Console.WriteLine("key=" + ig.Key + "");
                foreach (DataRow dr in ig)
                {                   
                    Console.WriteLine(dr["Name"].ToString().PadRight(10) + dr["Age"].ToString().PadRight(10) + dr["Score"].ToString().PadRight(10));
                }
                    

            }

            Console.ReadKey();
        }
    }
}

 

程序运行效果

 

posted @ 2019-09-10 10:13  .NET开发菜鸟  阅读(10208)  评论(0编辑  收藏  举报