Accepted answer

If you don't need Console.WriteLine(...) your code can be summarized with LINQ :

List<EmployeeTelDir> telDir = (from empl in lclEmployees
                               group empl by empl.Name into employeeGroup
                               select new EmployeeTelDir
                                   Name = employeeGroup.Key,
                                   Phone = (from employee in employeeGroup
                                           select employee.Phone).ToList()  // The ToList() is the Holy Grail of the LINQ queries

For the inverted operation:

List<EmployeeLocalRegister> inverse = (from employeeTelDir in telDir
                                       from phone in employeeTelDir.Phone  // Doing 2 from ... in ... successively corresponds to the SelectMany() LINQ method
                                       select new EmployeeLocalRegister
                                           Name = employeeTelDir.Name,
                                           Phone = phone


The lambda way:

var telDir = lclEmployees.GroupBy(e => e.Name, 
                                  (n, p) => new EmployeeTelDir 
                                              Name = n, 
                                              Phone = p.Select(k => k.Phone).ToList() 

Related Articles