Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: Query a collection within a collection

I have following structure:

public class Customer
{
  public int ID { get; set; }
  public List<Order> Orders { get; set; }
}

public class Order
{
  public int ID { get; set; }
  public int ProductID { get set; }
}

I need to get the collection of customers that ordered ProductID = 6. What would the fluent style LINQ look like?

I tried below with no luck:

var customers = allCustomers.SelectMany(c => c.Orders.Select(o => o.ProductID.Equals(6))).ToArray();
like image 538
Deepfreezed Avatar asked Jul 14 '11 18:07

Deepfreezed


1 Answers

var customers = allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6));

like image 196
Kirill Polishchuk Avatar answered Sep 27 '22 02:09

Kirill Polishchuk