Linq DataTable Group By 分組顯示人員明細

實現功能:spa

     

多個字段分組源碼樣例:code

原始數據:orm

 

分組後的輸出結果:blog

源代碼:源碼

 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         }
相關文章
相關標籤/搜索