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;
}
}
我正在使用上面的代码将 a 转换List<EmployeeLocalRegister>
为List<EmployeeTelDir>
. 这是唯一的优化方式吗?
我可以使用 Linq 查询List<EmployeeLocalRegister>
为来回转换编写更简单的代码吗?List<EmployeeTelDir>