LINQ:连接三个表的“组连接”功能

时间:2010-07-21 01:42:48

标签: vb.net linq

我已经搜索过以前的问题,似乎无法找到我想要的内容,所以请原谅n00b LINQ问题...我正在努力熟悉LINQ,并开始理解语法和用法。

在我的练习中,我整理了以下查询:

Dim r2 = From cust In cData.Customers _
                      Group Join ord In cData.Orders
                      On cust.CustomerID Equals ord.CustomerID
                      Into custorders = Group

我理解这个查询,它为我提供了我的cust对象,然后是每个cust对象的IEnumerable custorders集合。

我似乎无法弄清楚,是如何实现相同格式的结果,但使用Group Join添加第三个表“Products”,这样我就可以返回“ProductName”和“ProductPrice”等“Products”字段”

我有以下三个来源:

Public Customers As New List(Of Customer)
Public Products As New List(Of Product)
Public Orders As New List(Of Order)

相关领域是:

Orders.OrderID
Orders.OrderDate
Orders.CustomerID
Orders.ProductID
Customers.CustomerID
Customers.FirstName
Customers.LastName
Products.ProductID
Products.ProductName
Products.ProductPrice

我想我的第一个问题是我现在应该使用群组加入吗?如果是这样,我将如何撰写查询?如果没有,是否有一种简单,直接的方法来使用LINQ实现相同的结果?

任何帮助将不胜感激!

更新

我想出了以下查询,它似乎解决了我的问题:

Dim r4 = From cust In cData.Customers, ord In cData.Orders, _
                 prod In cData.Products _
                 Where ord.CustomerID = cust.CustomerID And _
                 ord.ProductID = prod.ProductID _
                 Group ord, prod By cust Into custorders = Group

所以我想我现在的问题是,这是实现目标的最好方法吗?或者使用其他方法会更有效率吗?

1 个答案:

答案 0 :(得分:0)

如果您真正想要的是3级层次结构,请尝试:

Dim orderProds = From order In cData.Orders _
          Group Join prod In cData.Products _
          On order.ProductID Equals prod.ProductID Into OrderProducts = Group

Dim customerOrderProducts = From cust In cData.Customers _
                            Group Join ordProd In orderProds _
                            On cust.CustomerID Equals ordProd.order.CustomerID Into custOrderProds = Group