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

如果选择了跑车类别,则其外观应如下所示。

汽车1-本田,汽车2-宝马,汽车3-本田,汽车4-梅赛德斯,汽车5-本田

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

汽车1,汽车3,汽车5

德丁根

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

除此之外,你可以用明示或内部的地方,所以这样的事情

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();

应该做。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章