![](/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.