是否可以在Linq.Where()期间过滤子集合?

时间:2015-12-16 11:11:49

标签: c# linq

我有一个对象heirarchy:

DeathStar.Floors.Departments.Rooms

目前,我只选择包含部门的地板,这些部门的房间内有反叛者浮渣被吓倒或被机器人注射:

var rebelScum = deathStar.Floors.Where(
                f=> f.Departments.Any(
                    d => d.Rooms.Any(
                        r => r.Occupant.Allegiance  == "Rebel"
                            && (r.InterrogationState == Interrogation.Intimidation
                                || r.InterrogationState == Interrogation.FloatyStabbyDroid)
                        )
                    )
                );

然而,rebelScum将包含与被查询的任何反叛者浮渣相同的部门中的空房间。

我可以在此.Where()内过滤以仅返回占用的房间吗?

1 个答案:

答案 0 :(得分:3)

  IEnumerable<Room> roomsOccupiedByRebelScum = deathStar.Floors.SelectMany(f => f.Departments)
                                                .SelectMany(d => d.Rooms)
                                                .Where(r => r.Occupant != null && r.Occupant.Allegiance == "Rebel" && 
                                                (r.InterrogationState == Interrogation.Intimidation || r.InterrogationState == Interrogation.FloatyStabbyDroid)
                                                );

如果您想过滤房间,他们必须形成查询结果