帮助LINQ投影

本文关键字:投影 LINQ 帮助 | 更新日期: 2023-09-27 17:49:47

我有一个ICollection<Product>:

var products = productRepository.FindAll();

Product有一个叫做Orders的属性,它是一个ICollection<Order>

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

换句话说:

给定一个产品集合,我想检索一个特定客户的订单列表

我有:

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>

我必须做一些分组吗?

帮助LINQ投影

怎么样:

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

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

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