簡體   English   中英

選擇集合在另一個集合(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;
    }
}

如果您需要更多信息,請告訴我,我將更新問題。

我會嘗試以下方法:

  1. 合並第一個和第二個Where謂詞
  2. All / Any替換Intersect (我假設RegionSearch具有ID唯一標識符)
  3. 如果仍然有問題,我將使用SQL事件探查器查看生成的SQL

更新

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM