有时候我们从数据库中查询出来数据之后,需要按照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 byvar query = from p in dt.AsEnumerable()group p by new { name = p.Field<string>("Name"),score=p.Field<Int32>("Score") } into mselect 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();}} }
程序运行效果