如何查询子对象

时间:2013-11-12 22:00:52

标签: c# linq

public class Employee
{
   public int Id { get; set; } 
   public string Title { get; set;} 
   //....other fields....
   //......
   //public Topics Interest { get; set; }     
   public IList<Topics> Interests { get; set; }     
}


public class Topics
{
   public int Id { get; set; }  ;
   public string Name { get; set; }  ;
   //other fields
}

public static IQueryable<EmployeeObject> QueryableSQL()
{
    IQueryable<EmployeeObject> queryable = EmployeeRepository.GetAllEmployee(); 
}

我的上述数据结构有Employee,其中有多个兴趣,每个兴趣都有多个主题

我的问题是:

我如何搜索Employee.Interests.Name?

   //i need help construct the linq....
   //the below will not work and look for something in the `EmployeeObject` rather in `Interests`
   IList<EmployeeObject> _emps = QueryableSQL().Where(x => x.Name== "Chess").ToList();

2 个答案:

答案 0 :(得分:2)

您可以在子集合上使用Any来查找匹配的EmployeeObject s

IList<EmployeeObject> _emps = 
    QueryableSQL().Where(x => x.Interests
                               .Any(i => i.Name== "Chess"))
                  .ToList();

答案 1 :(得分:2)

这取决于你想要什么。您是否想要任何兴趣与给定值相匹配的项目?

var query = QueryableSQL().Where(employee => 
    employee.Interests.Any(interest => interest.Name ==  "Chess"));

当您能够用英语解释时,您想要翻译成LINQ的查询将会更容易。