Linq中的where in子句

4

我有一个层次结构,其中部门包含团队,团队包含代表。我的目标是获取属于给定部门的代表列表。我尝试使用以下方式实现:

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;

但是团队集合不允许您像访问集合一样引用特定属性。我的意思是“选择所有在团队集合中具有TeamIDs的代表。”

4个回答

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

虽然这直接回答了问题,但我认为值得注意的是,我表达的方式(使用两个SelectMany调用)更加简单明了。 - Timothy Shields

2
我认为你可以在这里使用join。
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;

1
var delegates = db.Departments
    .Where(department => department.ID == 123)
    .SelectMany(department => department.Teams)
    .SelectMany(team => team.Delegates);

1
 var TeamDelegates = db.Teams
                 .Where(tms => tms.DepartmentID == DepartmentID)
                 .SelectMany(tms => db.J_TeamDelegates
                                      .Where(tds => tds.TeamID == tms.TeamID))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接