使用Linq进行分组

class Program
{
    static void Main(string[] args)
    {
        List<EmployeeLocalRegister> lclEmployees = new List<EmployeeLocalRegister>() { 
            new EmployeeLocalRegister(){Name = "A", Phone= "A1"}, 
            new EmployeeLocalRegister(){Name = "B", Phone= "B1"},
            new EmployeeLocalRegister(){Name = "A", Phone= "A2"}, 
            new EmployeeLocalRegister(){Name = "B", Phone= "B2"},
            new EmployeeLocalRegister(){Name = "B", Phone= "B3"},
            new EmployeeLocalRegister(){Name = "C", Phone= "C1"}};

        List<EmployeeTelDir> telDir = new List<EmployeeTelDir>();

        var queryEmployeeLocalRegisterByName =
        from empl in lclEmployees
        group empl by empl.Name;

        foreach (var employeeGroup in queryEmployeeLocalRegisterByName)
        {
            Console.WriteLine(employeeGroup.Key);
            List<string> phone = new List<string>();
            foreach (EmployeeLocalRegister employee in employeeGroup)
            {

                Console.WriteLine("    {0}", employee.Phone);
                phone.Add(employee.Phone);
            }

            telDir.Add(new EmployeeTelDir() { Name = employeeGroup.Key, Phone = phone });
        }

        Console.ReadKey();
    }
}

public class EmployeeLocalRegister
{
    public string Name;
    public string Phone;
}

public class EmployeeTelDir
{
    public string Name;
    public List<string> Phone;
}

}

我使用上面的代码转换List< EmployeeLocalRegister>列出< EmployeeTelDir>.这是唯一的优化方式吗?

我可以编写更简单的代码来进行List< EmployeeLocalRegister>的来回转换吗?列出< EmployeeTelDir>反之亦然使用Linq查询?

最佳答案 如果您不需要Console.WriteLine(…),您的代码可以使用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
                               }).ToList();

对于倒置操作:

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
                                       }).ToList();
点赞