2009-09-01 42 views
1

我試圖動態地創建表達式樹。Linq內連接分組

讓asume我有兩個簡單的類:

class CustomerType 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public OrderType[] Orders { get; set; } 
} 

class OrderType 
{ 
    public int Id { get; set; } 
    public DateTime Date { get; set; } 
    public decimal Price { get; set; } 
} 

..和相應的實體類型沒有任何關聯(所以,我需要使用自定義的連接)。

我需要使用相應的訂單來填充客戶列表。 我知道在Linq中有兩種連接:左外連接和左內連接。

因此,使用左外連接我可以寫出如下的查詢中(爲了簡化,我將使用LINQ表達式而不是自定義ExpressionTree發生器代碼說明的問題):

var query = from c in db.Customers 
      join o in db.Orders on c.Id equals o.CustomerId into g 
      select new AccountType() 
      { 
       Id = c.Id, 
       Name = c.Name, 
       Orders = g 
      }; 

所以,一個訂單屬性AccountType對象將包含所有對應的訂單。

我只是不明白如何使用左內部聯接來獲得與過濾相同的結果,基於訂單表字段(例如,我需要查詢所有訂單的價格更高的客戶比100.00):

var query = from c in db.Customers 
      join o in db.Orders on c.Id equals o.CustomerId 
      where o.Price > 100.00 
      select new AccountType() 
      { 
       Id = c.Id, 
       Name = c.Name, 
       Orders = ??? 
      }; 

感謝您的幫助!

+0

你所謂的「左外連接」實際上是調用Linq的「團隊合作」。 Linq不是SQL,SQL概念不直接轉換成Linq。 – 2009-09-01 09:52:10

+0

謝謝你的糾正。 – junglit 2009-09-01 10:51:28

回答

2

我會做這樣的:

var query = from c in db.Customers 
      join o in db.Orders on c.Id equals o.CustomerId into g 
      select new AccountType() 
      { 
       Id = c.Id, 
       Name = c.Name, 
       Orders = g.Where(o => o.Price > 100.00) 
      }; 

隨着內部聯接,你將不得不使用一個group by條款:

var query = from c in db.Customers 
      join o in db.Orders on c.Id equals o.CustomerId 
      where o.Price > 100.00 
      group o by c into g 
      select new AccountType() 
      { 
       Id = g.Key.Id, 
       Name = g.Key.Name, 
       Orders = g 
      } 
+0

非常感謝您的幫助! 「由...組成」的例子就是我需要的。 – junglit 2009-09-01 10:49:15