实现功能:
多个字段分组源码样例:
原始数据:
分组后的输出结果:
源代码:
1 public static void PrintPersons() 2 { 3 //准备数据 4 DataTable dt = new DataTable(); 5 dt.Columns.Add(new DataColumn("ID", typeof(int))); 6 dt.Columns.Add(new DataColumn("UserName", typeof(string))); 7 dt.Columns.Add(new DataColumn("DeptNo", typeof(string))); 8 dt.Columns.Add(new DataColumn("DeptName", typeof(string))); 9 DataRow drTemp = null; 10 for (int i = 10; i <= 18; i++) 11 { 12 drTemp = dt.NewRow(); 13 drTemp["ID"] = i; 14 drTemp["UserName"] = "姓名" + i.ToString(); 15 16 if (i < 15) 17 { 18 drTemp["DeptNo"] = "0001"; 19 drTemp["DeptName"] = "人事部"; 20 } 21 else 22 { 23 drTemp["DeptNo"] = "0002"; 24 drTemp["DeptName"] = "生产部"; 25 } 26 dt.Rows.Add(drTemp); 27 } 28 29 Console.WriteLine("分组前:"); 30 foreach (DataRow row in dt.Rows) 31 { 32 Console.WriteLine(string.Format("{0} {1} {2} {3} ", row.ItemArray)); 33 } 34 Console.WriteLine(""); 35 36 Console.WriteLine("分组后:"); 37 38 //Linq分组查询,并按分组显示人员明细 39 var query = from g in dt.AsEnumerable() 40 group g by new { t1 = g.Field<string>("DeptNo"), t2 = g.Field<string>("DeptName") } into companys 41 select new { DeptNo = companys.Key.t1, DeptName = companys.Key.t2, StallInfo = companys }; 42 43 foreach (var userInfo in query) 44 { 45 System.Collections.Generic.List<DataRow> dataRows = userInfo.StallInfo.ToList(); 46 47 Console.WriteLine(string.Format("{0}({1})人员名单: ", userInfo.DeptName, userInfo.DeptNo)); 48 foreach (System.Data.DataRow dr in dataRows) 49 { 50 Console.WriteLine(string.Format("{0} {1} ", dr.ItemArray)); 51 } 52 } 53 Console.ReadLine(); 54 }