LINQ: Query a collection within a collection
I have following structure:
开发者_JAVA百科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();
var customers = allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6));
allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6))
var customers = allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6));
Looks like you want:
var query = allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6));
A nice way would be to try from the other side like this
var customers from p in Order where p.ProductId == 6 select p.Customer
And of course you need the add the Customer property in the Order class like this
public class Order
{
public int ID { get; set; }
public int ProductID { get set; }
public Customer Customer { get; set; }
}
精彩评论