使用Linq进行分组

使用Linq进行分组,第1张

概述class Program{ static void Main(string[] args) { List<EmployeeLocalRegister> lclEmployees = new List<EmployeeLocalRegister>() { new EmployeeLocalRegister(){Name = "A", Ph
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();
总结

以上是内存溢出为你收集整理的使用Linq进行分组全部内容,希望文章能够帮你解决使用Linq进行分组所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1230797.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存