帮助LINQ Projection

时间:2011-04-13 03:58:56

标签: c# linq .net-4.0 linq-to-objects

我有一个ICollection<Product>

var products = productRepository.FindAll();

Product有一个名为Orders的属性,即ICollection<Order>

对于给定的 CustomerId ,我正试图以ICollection<Order>结束。

换句话说:

  

鉴于产品系列,我想检索特定客户的订单列表

这就是我所拥有的:

var orders = products
               .Where(x => x.Orders != null)
               .Where(x => x.Orders.Any(y => y.CustomerId == 10))
               .Select(x => x.Orders)
               .ToList();

但我最终得到List<ICollection<Order>>,我想要一个ICollection<Order>

我是否必须进行某种分组?

2 个答案:

答案 0 :(得分:5)

怎么样:

var orders = products
           .Where(x => x.Orders != null)
           .Where(x => x.Orders.Any(y => y.CustomerId == 10))
           .SelectMany(x => x.Orders)
           .ToList();

答案 1 :(得分:0)

如果您想收集单个产品的订单,那么这将起作用

var orders = products
               .Where(x => x.Orders != null)
               .Where(x => x.Orders.Any(y => y.CustomerId == 10))
               .Select(x => x.Orders)
               .Single();