group by 显示
public static void PrintPersons() { //准备数据 DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("ID", typeof(int))); dt.Columns.Add(new DataColumn("UserName", typeof(string))); dt.Columns.Add(new DataColumn("DeptNo", typeof(string))); dt.Columns.Add(new DataColumn("DeptName", typeof(string))); DataRow drTemp = null; for (int i = 10; i <= 18; i++) { drTemp = dt.NewRow(); drTemp["ID"] = i; drTemp["UserName"] = "姓名" + i.ToString();
if (i < 15) { drTemp["DeptNo"] = "0001"; drTemp["DeptName"] = "人事部"; } else { drTemp["DeptNo"] = "0002"; drTemp["DeptName"] = "生产部"; } dt.Rows.Add(drTemp); }
Console.WriteLine("分组前:"); foreach (DataRow row in dt.Rows) { Console.WriteLine(string.Format("{0} {1} {2} {3} ", row.ItemArray)); } Console.WriteLine("");
Console.WriteLine("分组后:");
//Linq分组查询,并按分组显示人员明细 var query = from g in dt.AsEnumerable() group g by new { t1 = g.Field<string>("DeptNo"), t2 = g.Field<string>("DeptName") } into companys select new { DeptNo = companys.Key.t1, DeptName = companys.Key.t2, StallInfo = companys };
foreach (var userInfo in query) { System.Collections.Generic.List<DataRow> dataRows = userInfo.StallInfo.ToList();
Console.WriteLine(string.Format("{0}({1})人员名单: ", userInfo.DeptName, userInfo.DeptNo)); foreach (System.Data.DataRow dr in dataRows) { Console.WriteLine(string.Format("{0} {1} ", dr.ItemArray)); } } Console.ReadLine(); }