如何在 C# 中将 List<string> 转换为 List<object> 特定属性

Sam*_*han -5 .net c# linq

如何在c#中转换List<string>List<object>属性

我们有一个电子邮件 ID 列表

List<string> str= new List<string>{"abc1@gmail.com","abc2@gmail.com"};
Run Code Online (Sandbox Code Playgroud)

现在我们必须将这些电子邮件 ID 分配给员工 emailId 属性的列表List<Employee>

var emplist = new List<Employee>() ;
Run Code Online (Sandbox Code Playgroud)

Pra*_*kar 7

您可以使用Select()

var emplist = str.Select(x => new Employee { EmailId = x }).ToList();
Run Code Online (Sandbox Code Playgroud)

Select()用于将序列的每个元素(在您的情况下是字符串 email id)投影到新序列(即Employee对象)中。