【问题标题】:How to filter a list where I need multiple dynamic filter parameters如何过滤需要多个动态过滤器参数的列表
【发布时间】:2012-09-03 18:32:34
【问题描述】:

我有一个对象列表(位置)。每个位置都可以有多个类别。我有一个整数列表(CategoryId)。基于此,我需要过滤位置:

List<int> categoriesToLoad = new List<int>();
// fill list
var allLocations = locationRepository.GetLocations().Where(...
var filteredLocations = from m in model
                             where categoriesToLoad.Contains(m.LocationCategories.FirstOrDefault() == null ? -1 : m.LocationCategories.FirstOrDefault().PlaceCategoryId)
                             select m;

这仅适用于一个类别,我不知道如何修复代码以比较附加到位置的所有类别。

【问题讨论】:

标签: c# linq entity-framework


【解决方案1】:

你想要Any。

var filteredLocations = 
       model.Where(m => m.LocationsCategories
            .Any(c => categoriesToLoad.Contains(c.PlaceCategoryId)));

【讨论】:

    【解决方案2】:

    尝试替换这个:

    var filteredLocations = from m in model
                            where categoriesToLoad.Contains(m.LocationCategories.FirstOrDefault() == null ? -1 : m.LocationCategories.FirstOrDefault().PlaceCategoryId)
                            select m;
    

    用这个:

    var filteredLocations = from m in model
                            where m.LocationCategories.Any(x => categoriesToLoad.Contains(x.PlaceCategoryId)
                            select m;
    

    虽然我并不完全理解你想要做什么以及你的应用程序的逻辑是什么,所以我所说的可能都是废话。

    【讨论】:

      【解决方案3】:

      你可以这样做:

      var filteredLocations = locationRepository
                                  .GetLocations()
                                  .Where(l => l.LocationCategories.Any(x => categoriesToLoad.Contains(x.PlaceCategoryId));
      

      【讨论】:

        猜你喜欢
        • 2014-07-29
        • 2021-05-13
        • 1970-01-01
        • 1970-01-01
        • 2020-12-23
        • 2013-02-16
        • 2014-06-09
        • 2023-01-23
        • 2017-05-19
        相关资源
        最近更新 更多