2011-04-13 102 views
1

我有一個ICollection<Product>幫助與LINQ投影

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>。我需要做某種分組嗎?

回答

5

關於什麼:

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

是的,這就是它 - 由於某種原因,我完全忘了'SelectMany'。乾杯! – RPM1984 2011-04-13 04:19:07

0

如果你想訂單單一產品的集合,然後這會工作

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

謝謝,但那不是我想要的。 – RPM1984 2011-04-13 04:25:14

+1

@ RPM1984沒關係,今天我在LINQ學習了'SelectMany'。非常感謝你和@zerkms ...:D – 2011-04-13 04:28:56