Linq where in clause

本文关键字:clause in where Linq | 更新日期: 2023-09-27 18:00:15

我有一个层次结构,其中部门包含团队,团队包含代表。我想做的是得到一份特定部门下的代表名单。我试着这样做:

var teams = from tms in db.Teams
            where tms.DepartmentID == DepartmentID
            select tms;
var TeamDelegates = from tds in db.J_TeamDelegates
                    where tds.TeamID in teams.TeamID //error here
                    select tds;

但是teams集合不允许您引用特定的属性,就好像它是一个集合一样。我想说的是"选择团队集合中所有具有TeamID的代表。"

Linq where in clause

var TeamDelegates = from tds in db.J_TeamDelegates
                    where teams.Any(x => x.TeamID == tds.TeamID)
                    select tds;

我认为您可以在这里使用联接。

var TeamDelegates = from tms in db.Teams
                    where tms.DepartmentID == DepartmentID
                    join tds in db.J_TeamDelegates on tms.TeamID equals tds.TeamID
                    select tds;
 var TeamDelegates = db.Teams
                 .Where(tms => tms.DepartmentID == DepartmentID)
                 .SelectMany(tms => db.J_TeamDelegates
                                      .Where(tds => tds.TeamID == tms.TeamID))
var delegates = db.Departments
    .Where(department => department.ID == 123)
    .SelectMany(department => department.Teams)
    .SelectMany(team => team.Delegates);