tags:

views:

53

answers:

1
+4  Q: 

LINQ Nested Where

If I have the following model;

  public List<RecommendedProduct> recommendations

Then

public class RecommendedProduct
  public List<Product> Products

Then the Product;

public class Product
  public string Code

The recommendations list has, as an example, 10 items in it.

Each recommendations item has two Products in it.

How, with LINQ, can I find the recommendations object that has products with both "A" and "B" product codes?

+5  A: 

Use the Any extension:

var myProducts =
    from rp in recommendations
    where
        cp.Products.Any(p => p.Product.Code == "A") &&
        cp.Products.Any(p => p.Product.Code == "B")
    select rp;

Any returns true if there are any elements in the sequence that match the inner condition. In this case you're searching for two elements, so it takes two Any calls.

Aaronaught
+1 Brilliant! Thanks @Aaronaught.
griegs