嵌套LINQ查询选择

本文关键字:选择 查询 LINQ 嵌套 | 更新日期: 2023-09-27 18:17:10

请考虑以下示例类构造:

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!");
}

这工作得很好;但是,如果我只想检索一段数据而不获取索引,那么它似乎相当臃肿。还有别的办法吗?

嵌套LINQ查询选择

您可以使用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!");
}