微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用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"},Phone= "B2"},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();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐