linq searching matching items in child collection
I am looking for a way to do a IN clause query on child collections in linq.
I have a an example as follows:
Entity: Product.CategoryAssignments - this is an IList<Category> that the product is assigned to. Product can be assigned to multiple categories.
开发者_如何学CI want to retrieve all products matching in a list of categories i.e.
IList<Category> selectedCategories = GetUsersSelectedCategories();
// how to do something like
IList<Products> products = from p in repository where p.CategoryAssignments.Contains(?) select p;
Any tips appreciated?
Unless I'm mis-understanding the question, I don't think the answer is actually about how to do 'in' statement in Linq, because you're actually comparing the results of two lists.
I'm not an expert at this, as I don't use Linq on a day to day basis (I'm an NH Criteria person), but what you really want here is either a union or dynamically constructed set of OR statements?
"Give me all the products where the category is this or this or this"
Or
"Give me all the products where the category is this"
union
"Give me all the products where the category is this"
union
"Give me all the products where the category is this"
Because I'm not all that au-fait with Linq, I'm not going to attempt to construct the statement for this, but I'm willing to bet it's a well documented problem out there on the internets? :)
[Edit] Went and looked it up - does something like this work?
var query =
from p in products
where p.Categories.Any(c=> selectedCategories.Contains(c))
select p;
Where categories is your list of categories you are comparing against
精彩评论