Reputation: 103
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();
I'm sending 2 arrays.
categoryIds & brandsIds
I pass the ones matching categoryIds to the carList var into View, but with the query "or", if the customer chooses a brand in addition to the category, I want to pass two queries.
If the sports car category is selected, it should look like the following.
Car1 - Honda, Car2 - Bmw, Car3 - Honda, Car4 - Mercedes, Car5 - Honda
If the sports car category is selected and the brand is selected, it should look like the following.
Car1, Car3, Car5
Upvotes: 0
Views: 352
Reputation: 382
I'd suggest you don't use "a" twice, you're using it once for the entries in allCars but also for those in a.CarCategory. May use some detailed names like
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();
Aside from that, you can just use explicit or inside that where, so something like this
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();
should do.
Upvotes: 1
Reputation: 43860
try to use this query:
carList = allCars.
Where(a => categoryIds.Contains(a.CarId)
&&(
(brandsIds=null
|| brandsIds.Length ==0)
)
|| brandsIds.Contains(a.BrandId)
)
)
.ToList();
Upvotes: 1