Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Nested Where

Tags:

linq

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?

like image 382
griegs Avatar asked Apr 21 '10 03:04

griegs


1 Answers

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.

like image 97
Aaronaught Avatar answered Oct 09 '22 16:10

Aaronaught