在LINQ中过滤相关表

时间:2011-06-09 23:21:40

标签: linq linq-to-entities

假设我有一个公司表,一个Employees表,而Employees表有一个FK列到Companies表。查询公司并返回相关员工非常容易。

var companies = from c in Companies
                select c;

通过添加where子句来过滤这些公司非常容易。但是如何过滤上面查询中返回的员工。例如,仅包括那些Employed列为true的员工?

我想退回所有公司,只有那些目前就业的员工。

3 个答案:

答案 0 :(得分:4)

检索受雇的公司及其雇员:

var companies = from c in Companies
                select new
                {
                    Company = c,
                    EmployedPersons = c.Employees.Where(e => e.Employed)
                };

像这样使用:

foreach (var company in companies)
{
    Console.WriteLine("{0}", company.Company);
    foreach (var employee in company.EmployedPersons)
    {
        Console.WriteLine("{0}", employee);
    }
}

另一种方法,根据您的评论,您需要在其他地方过滤此内容:

public void DisplayEmployedPersons(Company company)
{
    foreach (var employee in company.Employees.Where(e => e.Employed))
    {
        Console.WriteLine("{0}", employee);
    }
}

最后,您可以修改为Customer数据对象生成的分部类:

public partial class Customer
{
    public IEnumerable<Employee> CurrentEmployees
    {
        get { return this.Employees.Where(e => e.Employed);
    } 
}

答案 1 :(得分:3)

我不确定你想对员工做什么,但这是一种迭代它们的方法:

var companies = from c in Companies
                where c.Employees.Any(e => e.Employed)
                select c;

foreach (var company in companies) {
    foreach (var employee in company.Employees.Where(e => e.Employed)) {
        // your employed employees are iterated here
    }
}

答案 2 :(得分:2)

使用查询语法:

var companies = from c in Companies
                from e in c.Employees
                where e.Employed
                select c;