我有以下结构:
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; }
}
我需要获得订购ProductID = 6的客户的集合。流畅的样式LINQ会是什么样的?
我试着在下面没有运气:
var customers = allCustomers.SelectMany(c => c.Orders.Select(o => o.ProductID.Equals(6))).ToArray();
答案 0 :(得分:9)
var customers = allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6));
答案 1 :(得分:3)
allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6))
答案 2 :(得分:2)
var customers = allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6));
答案 3 :(得分:2)
看起来你想要:
var query = allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6));
答案 4 :(得分:0)
一个很好的方法就是从另一边尝试这样的
var customers from p in Order where p.ProductId == 6 select p.Customer
当然,您需要在Order类中添加Customer属性,如此
public class Order
{
public int ID { get; set; }
public int ProductID { get set; }
public Customer Customer { get; set; }
}