我有以下代码:
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
答案 0 :(得分: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);
}
}