RickL
RickL

Reputation: 3393

LINQ lambda for many to many relationship

There is a many-to-many data relationship between Products and CategoryGroups and I'm selecting all the Products (from a starting point of productList) that are also in specific CategoryGroups (the list of CategoryGroup Ids is given in groupIds).

This can be successfully achieved using the following LINQ expression:

productList =
    from p in productList
    where (
    from g in p.CategoryGroup
    where groupIds.Contains(g.CategoryGroupId)
    select g
    ).Any()
    select p;

where:

var productList = db.Products
    .Where(a => a.ThisCondition == thisCondition)
    .ToList();  

var groupIds = db.CategoryGroups
    .Where(a => a.ThatCondition == thatCondition)
    .Select(a => a.CategoryGroupId)
    .ToList();

Is it possible to replace the productList LINQ expression with one LINQ lambda expression ?

Any help much appreciated.

Upvotes: 2

Views: 1092

Answers (1)

ocuenca
ocuenca

Reputation: 39326

If you have represented your many to many relationship using two collection navigation properties like in this tutorial, you can simplify your queries to this:

var productList = db.Products
                    .Where(a => a.ThisCondition == thisCondition 
                                && a.CategoryGroups.Count(c=>groupIds.Contains(c.CategoryGroupId))>0);

Or you could also use Any extension method:

var productList = db.Products
                    .Where(a => a.ThisCondition == thisCondition 
                                && a.CategoryGroups.Any(c=>groupIds.Contains(c.CategoryGroupId)));

Upvotes: 3

Related Questions