Domanda

I've the following code:

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);
}

How have I change my code so that the output is as follows:

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
È stato utile?

Soluzione

You need a group by clause and another foreach loop to print employees:

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);
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top