请考虑以下示例类构造:
public class Company
{
public string CompanyName { get; set; }
public List<Subdivision> Subdivisions { get; set; }
}
public class Subdivision
{
public string SubdivisionName { get; set; }
public List<Employee> Employees { get; set; }
}
public class Employee
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
}
List的示例变量:
List<Company> CompanyList = new List<Company>();
CompanyList.Add(new Company
{
CompanyName = "TestCompany",
Subdivisions = new List<Subdivision>
{
{ new Subdivision
{
SubdivisionName = "TestSubdivision",
Employees = new List<Employee>
{
{ new Employee
{
EmployeeID = 1,
EmployeeName = "John"
}
}
}
}}
}
});
我想通过EmployeeID获取EmployeeName。请考虑以下代码:
if (CompanyList.Any(x => x.Subdivisions.Any(y => y.Employees.Any(z => z.EmployeeID == 1))))
{
int i1 = CompanyList.IndexOf(CompanyList.Where(x => x.Subdivisions.Any(y => y.Employees.Any(z => z.EmployeeID == 1))).Select(x => x).First());
int i2 = CompanyList[i1].Subdivisions.IndexOf(CompanyList[i1].Subdivisions.Where(x => x.Employees.Any(z => z.EmployeeID == 1)).Select(x => x).First());
int i3 = CompanyList[i1].Subdivisions[i2].Employees.IndexOf(CompanyList[i1].Subdivisions[i2].Employees.Where(z => z.EmployeeID == 1).Select(x => x).First());
string i = CompanyList[i1].Subdivisions[i2].Employees[i3].EmployeeName;
Console.WriteLine(i);
}
else
{
Console.WriteLine("Employee with ID 1 not found!");
}
这很好用;但是,如果我只想在不获取索引的情况下检索一段数据,它似乎相当臃肿。还有其他方法吗?
答案 0 :(得分:1)
您可以使用SelectMany搜索所有公司所有部门的所有员工,然后使用FirstOrDefault确保在未找到员工的情况下返回null
var employee = CompanyList.SelectMany(company => company.Subdivisions.SelectMany(division => division.Employees))
.FirstOrDefault(emp => emp.EmployeeID == 1);
if (employee != null)
{
Console.WriteLine(employee.EmployeeName); //prints John
}
else
{
Console.WriteLine("Employee with ID 1 not found!");
}