I have a class that looks like
public class ProductCategory {
public int ProductCategoryId { get; set; }
public string ProductCategoryName { get; set; }
public List<Product> Products { get; set; }
and product has a few properties such as name, price etc.
I want a linq query that will return this structure of a product category with the array of products but only where a property of the product is equal to a value. For example where the price is 10.
I have tried
productCategory.SelectMany(p => p.Products).Where(x => x.Price == 10)
but this returns me an array of products but I want the product category with all the products that match the criteria.
As an extra challenge, I have multiple criteria as well, so in this example say prices are equal to 10, 30 or 50. There's an added complexity that one of the criteria has two values. I was going to do this just by calling the different selection criteria and then concatenate them at the end
var equalToTen = productCategory.Select... x.Price == 10
var equalToThirty = productCategory.Select... x.Price == 30
var equalToFiftyANdNameIsTest = productCategory.Select... x.Price == 50 && x.Name == "Test"
return equalToTen.Union(equalToThirty).Union(equalToFiftyANdNameIsTest)
but I'm sure that it can be done in a single statement without the need to concatenate at the end.
Update
The ProductCaegory isn't a single one either. It is the result of a EF query to the database. So it'll need to return multiple ProductCategories where the sub class Product query matches.
ProductCategorys as a result of your query but with a subset of elements in theirProductsproperty. This means that you either have to manipulate existingProductCategoryobjects or create new ones.