C#lambda表达式,子子查询

时间:2013-01-22 20:45:30

标签: c# linq lambda

我正在尝试查询对象层次结构,如:

客户 - >订单IList &安培; 订单 - >产品IList

我的Customer对象有一组订单,而我的Order对象有一组产品。

我想要做的是让订购特定产品的客户。我将通过product id进行查询。在查询结束时,我想获得Customer list

我尝试了这个,但它没有用。

public ICollection<Customer> GetByParticularProduct(int productId)
{

    return allCustomers
    .Where(customer => customer.Orders
.Any(order => order.Products
.Any(prod => prod.Id == productId)))
    .ToList();
}

我怎样才能解决这个问题?

2 个答案:

答案 0 :(得分:0)

如果您的馆藏可能包含null,那么您可以试试这个

public ICollection<Customer> GetByParticularProduct(int productId)
{
    return (from cust in allCustomers.Where(x => x != null)
            let orders = cust.Orders.Where(x => x != null)
            let prods = orders.SelectMany(x => x.Products).Where(x => x != null)
            where prods.Any(x => x.Id == productId)
            select cust)
           .ToList();
}

答案 1 :(得分:-1)

return allCustomers
    .Where(customer => customer.Orders
        .Any(order => order.Products
            .Any(prod => prod.Id == productId))).ToList();

return allCustomers
    .Where(customer => customer.Orders
        .Any(order => order.ProductId == productId))).ToList();