首页 > 代码库 > Linq DataTable Group By 分组显示人员明细
Linq DataTable Group By 分组显示人员明细
原始数据:
分组后的输出结果:
源代码:
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 else22 {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 companys41 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 }
Linq DataTable Group By 分组显示人员明细
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。