开发者

LINQ: "Group Join" functionality joining three tables

I've searched previous questions and can't seem to find what I'm looking for, so please excuse the n00b LINQ question... I'm working on becoming familiar with LINQ, and getting my head around the syntax and usage.

In my exercises, I put together the following query:

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

This query I understand, and it gives me my cust object and then IEnumerable custorders collection for each cust object.

What I can't seem to figure out, is how to achieve the same format of results, but add in a third table "Products" using Group Join so I can return "Products" fields like "ProductName" and "ProductPrice".

I have the following three sources:

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

The pertinent fields are:

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

I guess my first question is should I be using Group Join at this point? If so, how would I compose the query? If not, is there 开发者_开发问答a simple, straight-forward way to achieve the same results using LINQ?

Any help would be appreciated!

UPDATE:

I came up with the following query, and it seems to solve my problem:

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

So I guess my question at this point would be, is this the best way to accomplish my goal? Or would it be more efficient to use another method?


If what you really want is a 3 level hierarchy, then try:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜