说我有代码:
class Program
{
static void Main( string[] args )
{
Company companyA = new Company();
Company companyB = new Company();
companyA.Employees = new List<string> { "A1", "A2" };
companyB.Employees = new List<string> { "B1", "B2" };
List<Company> companyList = new List<Company> {companyA, companyB};
List<string> allEmployees = new List<string>();
foreach( Company company in companyList )
{
allEmployees.AddRange( company.Employees );
}
// ...
}
class Company
{
public List<string> Employees { get; set; }
}
}
我想在 companyList 中向所有公司的员工填写 allEmployees 。
通过在 companyList 对象上使用单个LINQ语句,是否可以获得相同的结果,而不是使用上面的代码?可能是这样的:
List<string> allEmployees = companyList.Select( ...? )
答案 0 :(得分:4)
使用SelectMany
List<string> allEmployees = companyList.SelectMany(x => x.Employees).ToList();
答案 1 :(得分:2)
您可以使用AddRange
+ SelectMany
:
allEmployees.AddRange( companyList.SelectMany(c => c.Employees) );
如果您不想将它们添加到现有列表中,而是创建一个新列表:
List<string> allEmployees = companyList.SelectMany(c => c.Employees).ToList();