我一直在研究linq查询几个小时但没有让它工作。
我试图将某些数据列表与另一个数据列表进行比较,但我不知道为什么它没有按预期工作。
我有一个DbSet,Room有一个设施清单,每个设施都有自己的ID。
所以我的方法采用了facilityId的列表(IEnumerable),我想返回与设施列表相匹配的所有房间。
所以我认为我的查询看起来像这样:
var rooms = DbSet.Include("Facility").Where(room => room.Facility.All(facility => facilityIds.Contains(facility.Id)));
但是这个查询给了我比预期更多的结果。任何人都可以帮我解决这个疑问吗?
更新示例
var filterIds = new int[] {1,2};
var facilities1 = new List<Facility> {new Facility() {Id = 1}};
var facilities2 = new List<Facility> {};
var facilities3 = new List<Facility> {new Facility() {Id = 1}, new Facility() {Id = 2}};
var basicData = new List<Room>()
{
new Room() {Id = 1, Facility = facilities1},
new Room() {Id = 2, Facility = facilities2},
new Room() {Id = 3, Facility = facilities1},
new Room() {Id = 4, Facility = facilities3},
new Room() {Id = 5, Facility = facilities1},
new Room() {Id = 6, Facility = facilities1},
};
var result = basicData.Where(r => (!filterIds.Any() || r.Facility.All(f => filterIds.Contains(f.Id))));
这个查询给了我6个结果,而且我只期待Id 4的房间。
答案 0 :(得分:3)
这会有用吗?
rooms.Where(
room => room.Facilities.Any()
&& filterIds.All(x => room.Facilities.Any(o => o.Id == x))
);
<强>更新强>
更新了您的示例数据。按设施4
的预期返回房间1,2
。仅返回设施1,3,4,5,6
的房间1
: