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进行分组所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)