If you want to return all products with all the categories provided in Categories , which means that he selects a product in which he has category1 and category2.
Then you need to use All with the Contains combination:
public List<Product> FilterProducts(List<Category> categories) { return products.Where(p => categories.All(c => p.Categories.Contains(c)) .ToList(); }
If you want to return the entire product in which it has the smallest number of cetegory from the categories provided, this means that it selects the product in which it has category1 or category2.
Then you need to use Any
public List<Product> FilterProducts(List<Category> categories) { return products.Where(p => categories.Any(c => p.Categories.Contains(c) .ToList(); }
Please, not that if your Categories objects do not match the instances that you have in the Product Categories property or in your Category , you do not override the Equals method to use Id you can compare Id instead of the category objects themselves.
So something like:
Solution with all
public List<Product> FilterProducts(List<Category> categories) { return products.Where(p => categories .All(c => p.Categories.Any(cat => cat.Id == c.Id)).ToList() }
Solution with any
public List<Product> FilterProducts(List<Category> categories) { return products.Where(p => categories .Any(cat => p.Categories.Any(pcat => pcat.Id == cat.Id)).ToList(); }
source share