【问题标题】:Linq: Adding the Where clause "or" conditionLinq:添加 Where 子句“或”条件
【发布时间】:2021-04-09 12:35:03
【问题描述】:
 carList = allCars.Where(a => a.CarCategory.Any(a => categoryIds.Contains(a.CarId))).ToList();
           &&
           allCars.Where(b => b.BrandCategory.Any(b => brandsIds.Contains(b.BrandId)).ToList();

我要发送 2 个数组。

categoryIds 和brandIds

我将匹配 categoryIds 到 carList var 的那些传递到 View,但是使用查询“或”,如果客户除了类别之外还选择了一个品牌,我想传递两个查询。

如果选择了跑车类别,它应该如下所示。

Car1 - 本田、Car2 - 宝马、Car3 - 本田、Car4 - 梅赛德斯、Car5 - 本田

如果选择了跑车类别并选择了品牌,它应该如下所示。

汽车 1、汽车 3、汽车 5

【问题讨论】:

  • && (brandIds.Count == 0 || b.BrandCategory.Any(b => brandsIds.Contains(b.BrandId)) ?
  • 如果选择了品牌,您是要返回匹配类别或品牌的那些,还是只返回同时匹配的那些?
  • @DerDingens 选择一个类别是强制性的,但品牌是可选的。如果同时选择了类别和品牌,我想返回两者都匹配的那些。我更新了代码。

标签: c# .net asp.net-mvc entity-framework linq


【解决方案1】:

我建议您不要使用“a”两次,您对 allCars 中的条目使用一次,但也对 a.CarCategory 中的条目使用它.可以使用一些详细的名称,如

carList = allCars.Where(currentCar => currentCar.CarCategory.Any(currentCarCategory => categoryIds.Contains(currentCarCategory.CarId))).ToList();
       &&
       allCars.Where(currentCar => currentCar.BrandCategory.Any(currentCarBrand => brandsIds.Contains(currentCarBrand.BrandId)).ToList();

除此之外,您可以在 where 中使用 explicit 或,所以像这样

carList = allCars
    // get those that match categoryIds
    .Where(currentCar => currentCar.CarCategory.Any(currentCarCategory => categoryIds.Contains(currentCarCategory.CarId)) 
    // to include brands
    && 
        // check if brands are provided
        (
            // in case they are not this will ignore the any below
            (brandIds == null || !brandIds.Any())
            ||  
            // in case there are, get those match the brands
            currentCar.BrandCategory.Any(currentCarBrand => brandsIds.Contains(currentCarBrand.BrandId))
        )
    .ToList();

应该这样做。

【讨论】:

    【解决方案2】:

    尝试使用这个查询:

    carList = allCars.
                Where(a => categoryIds.Contains(a.CarId)
               &&(
                     (brandsIds=null 
                    || brandsIds.Length ==0)
                     )
                     || brandsIds.Contains(a.BrandId)
                   )
                )
               .ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多