2014-03-30 101 views
0

我有下面的代碼:淨的LINQ集團通過加入

Departement[] dept = { 
    new Departement {Id = 'S', Name = "Sales" }, 
    new Departement {Id = 'R', Name = "R&D" }, 
    new Departement {Id = 'M', Name = "Marketing" }, 
    new Departement {Id = 'L', Name = "Logistics" }, 
}; 

Employee[] emp = { 
    new Employee {Id = 7, Name = "Peter Smith", Departement = 'S'}, 
    new Employee {Id = 9, Name = "Sam Brown", Departement = 'R'}, 
    new Employee {Id = 12, Name = "John Black", Departement = 'S'}, 
    new Employee {Id = 21, Name = "Sally White", Departement = 'S'}, 
    new Employee {Id = 18, Name = "Diego Maley", Departement = 'R'}, 
    new Employee {Id = 327, Name = "Anna Brown", Departement = 'M'} 
}; 

var res = from d in dept 
      from e in emp 
      join e in emp on d.Id equals e.Departement into cs 
      select new 
      { 
       Id = e.Id, 
       Name = e.Name, 
       count = cs.Count(), 
       departement = e.Departement 
      }; 

foreach (var p in res) 
{ 
    Console.WriteLine("{0} {1} {2}", p.Id, p.Name, p.departement); 
} 

怎麼會有我改變我的代碼,以便輸出如下:

S: Sales -> 3 employees 

    7: Peter Smith 

    12: John Black 

    21: Sally White 

R: R&D -> 2 employees 

    9: Sam Brwon 

    18: Diego Malley 

M: Marketing -> 1 employees 

    32: Anna Brown 

L: Logistics -> 0 employees 
+1

歡迎來到SO。你對目前的代碼有任何問題嗎?有什麼不工作? – Benesh

回答

2

你需要一個group by條款,另有foreach迴路打印員工:

var res = from d in dept 
      join e in emp on d.Id equals e.Departement into cs 
      from e in cs.DefaultIfEmpty() 
      group e by d into g 
      select new 
      { 
       Department = g.Key, 
       Employees = g.Where(x => x != null).ToList() 
      }; 

foreach (var p in res) 
{ 
    Console.WriteLine("{0} {1} {2}", p.Department.Id, p.Department.Name, p.Employees.Count); 
    foreach (var e in p.Employees) 
    { 
     Console.WriteLine("{0} {1}", e.Id, e.Name); 
    } 
} 
+0

你可能會解釋關鍵字「Key」:g.Key? – user3477008

+0

@ user3477008投票到有用的帖子,並檢查帖子,如果他們是你的答案 –