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>
转换为List<EmployeeTelDir>
。这是唯一的优化方法吗?
是否可以使用 Linq 查询编写更简单的代码来回转换从 List<EmployeeLocalRegister>
到 List<EmployeeTelDir>
,反之亦然?
如果你不需要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();
lambda 方式:
var telDir = lclEmployees.GroupBy(e => e.Name,
(n, p) => new EmployeeTelDir
{
Name = n,
Phone = p.Select(k => k.Phone).ToList()
}).ToList();