Linq:添加 Where 子句“或”条件

问题描述

 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 中,但是对于查询“or”,如果客户除了类别之外还选择了一个品牌,我想传递两个查询

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

Car1 - 本田,Car2 - 宝马,Car3 - 本田,Car4 - 奔驰,Car5 - 本田

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

车1、车3、车5

解决方法

尝试使用此查询:

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

我建议您不要使用两次“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();

应该这样做。