Linq 分组查询

 根据部门分组 ,然后存储部门下所有员工

 1  public class Custom
 2     {
 3         public string dname { get; set; }
 4         public List<Employees> lis { get; set; }
 5     }
 6     public class Employees
 7     {
 8         public string id { get; set; }
 9         public string name { get; set; }
10         public string depart { get; set; }
11     }
12 static void main()
13 {
14 DataTable dt = new DataTable();
15                 dt.Columns.Add(new DataColumn("id"));
16                 dt.Columns.Add(new DataColumn("name"));
17                 dt.Columns.Add(new DataColumn("depart"));
18 
19                 string[] s = { "1,a,.net", "2,b,.net", "3,c,.net", "4,h,ui", "5,i,ui", "6,j,ui" };
20                 foreach (string p in s)
21                 {
22                     DataRow dr = dt.NewRow();
23                     dr[0] = p.Split(',')[0];
24                     dr[1] = p.Split(',')[1];
25                     dr[2] = p.Split(',')[2];
26                     dt.Rows.Add(dr);
27                 }
28               
29                 var item = from p in dt.AsEnumerable()
30                            group p by p.Field<string>("depart") into d
31                            select new Custom
32                            {
33                                dname = d.Key,
34                                lis = dt.AsEnumerable().Where(a => a.Field<string>("depart") == d.Key)
35                                       .Select(a => new Employees { id = a.Field<string>("id"), name = a.Field<string>("name"), depart = a.Field<string>("depart") }).ToList<Employees>()
36                            };
37 }
原文地址:https://www.cnblogs.com/farmer-y/p/6136363.html