LINQ: collection request in collection

I have the 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 collect a collection of customers who ordered ProductID = 6. What would be the fluent LINQ style?

I tried below, no luck:

 var customers = allCustomers.SelectMany(c => c.Orders.Select(o => o.ProductID.Equals(6))).ToArray(); 
+4
source share
5 answers

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

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

It looks like you want:

 var query = allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6)); 
+2
source

A good way would be to try on the other hand, like this

 var customers from p in Order where p.ProductId == 6 select p.Customer 

And, of course, you need to add the Customer property to the Order class, like this

 public class Order { public int ID { get; set; } public int ProductID { get set; } public Customer Customer { get; set; } } 
0
source

All Articles