![](/img/trans.png)
[英]Select all fields from collection with related items in another collection using LINQ
[英]Select items where collection is in another collection (linq)
我在linq查询中苦苦挣扎,需要在其中查找与另一个集合中的id匹配的集合中的项目。
用户可以登录并保存属性搜索,您可以在其中指定是否要在公寓,房屋等以及哪些区域进行搜索。 然后,我们要显示搜索特定区域等的用户列表。
这是我尝试进行搜索的代码:
SearchSetting searchSetting = mySearchSetting;
List<RegionSearch> regionSearchList = myRegionSearchList;
var searches =
SearchSettingsRepository.Instance.Where(s =>
(!searchSetting.Flat || s.Flat == searchSetting.Flat) &&
(!searchSetting.House || s.House == searchSetting.House) &&
(!searchSetting.Castle || s.Castle == searchSetting.Castle),
new[] { "RegionSearches" })
.Where(s => s.RegionSearches.Intersect(regionSearchList)
.Any())
.ToList();
因此,如果myRegionSearchList包含RegionA和RegionB,则需要一个在SearchSetting.RegionSearches中指定了两个区域的所有用户的列表。 目前,即使我知道有些用户同时选择了两个区域,上述结果仍返回零结果。
我们首先使用Entity Framework数据库,并且有一个通用存储库,所有存储库都继承自该存储库,因此上述搜索正在调用此方法:
public abstract class GenericRepository<TDb, TModel>
where TDb : DbContext, new()
where TModel : class
{
public List<TModel> Where(Expression<Func<TModel, bool>> pred, string[] include = null)
{
List<TModel> items;
using (var db = new TDb())
{
if (include == null)
{
items = db.Set<TModel>().Where(pred).ToList();
}
else
{
DbQuery<TModel> query = null;
foreach (var inc in include)
{
query = db.Set<TModel>().Include(inc);
}
items = query.Select(t => t).Where(pred).ToList();
}
}
return items;
}
}
如果您需要更多信息,请告诉我,我将更新问题。
我会尝试以下方法:
Where
谓词 All
/ Any
替换Intersect
(我假设RegionSearch
具有ID
唯一标识符) 更新
List<RegionSearch> regionSearchList = myRegionSearchList;
List<int> regionSearchListIds = regionSearchList.Select(x => x.ID).ToList();
代码示例:
SearchSettingsRepository.Instance.Where(s =>
(!searchSetting.Flat || s.Flat == searchSetting.Flat) &&
(!searchSetting.House || s.House == searchSetting.House) &&
(!searchSetting.Castle || s.Castle == searchSetting.Castle) &&
regionSearchListIds.All(r => s.RegionSearches.Any(x => x.ID == r)),
new[] { "RegionSearches" });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.