在C#中如何将List<string>转换为List<Employee>并赋值emailId属性
我们有一个存储邮箱ID的List<string>集合,示例代码如下:
List<string> emailList = new List<string>{"abc1@gmail.com","abc2@gmail.com"};
同时已经初始化了一个List<Employee>类型的列表:
var employeeList = new List<Employee>();
现在需要把这些邮箱ID分别赋值给employeeList中每个对象的emailId属性,以下是几种可行的实现方式:
方案一:for循环遍历(适合需控制索引或处理长度差异的场景)
如果employeeList为空,需要先创建对应数量的Employee对象,再逐一赋值:
// 先创建与邮箱数量匹配的Employee对象并加入列表 for (int i = 0; i < emailList.Count; i++) { employeeList.Add(new Employee()); } // 遍历赋值,同时做索引越界检查 for (int i = 0; i < emailList.Count; i++) { if (i < employeeList.Count) { employeeList[i].emailId = emailList[i]; } }
方案二:LINQ简洁实现
如果不需要提前维护空列表,可以直接通过LINQ将邮箱列表转换为Employee列表:
var employeeList = emailList.Select(email => new Employee { emailId = email }).ToList();
若employeeList中已有Employee对象,且数量与邮箱列表一致,可用Zip方法配对赋值:
foreach (var pair in employeeList.Zip(emailList, (emp, email) => new { emp, email })) { pair.emp.emailId = pair.email; }
注意事项
- 需保证
employeeList和emailList的元素数量匹配,避免索引越界异常;若数量不匹配,需根据业务逻辑处理(比如忽略多余邮箱、给多余Employee赋值默认值等)。 - 假设
Employee类已定义emailId属性,示例定义如下:
public class Employee { public string emailId { get; set; } // 其他业务属性... }
内容的提问来源于stack exchange,提问作者Samadhan
相关产品推荐
相关产品推荐

