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();
        }
    }
}

 

程序運行效果express

相關文章
相關標籤/搜索