共用方式為


HOW TO:處理查詢中的複合索引鍵 (LINQ to SQL)

更新: November 2007

有些運算子只能取用一個引數。如果引數必須包括資料庫中的多個資料行,則必須建立匿名型別來表示此項組合。

範例

下列範例顯示叫用 (Invoke) GroupBy 運算子的查詢,這個運算子只可以取用一個 key 引數。

Dim query = _
From cust In db.Customers _
Group cust.ContactName By Key = New With {cust.City, cust.Region} _
Into Group

For Each grp In query
    Console.WriteLine("Location Key: {0}", grp.Key)
    For Each listing In grp.Group
        Console.WriteLine(vbTab & "0}", listing)
    Next
Next
        var query =
from cust in db.Customers
group cust.ContactName by new { City = cust.City, Region = cust.Region };

        foreach (var grp in query)
        {
            Console.WriteLine("\nLocation Key: {0}", grp.Key);
            foreach (var listing in grp)
            {
                Console.WriteLine("\t{0}", listing);
            }
        }

聯結 (Join) 的情況也相同,如下列範例所示:

Dim query = From ord In db.Orders, prod In db.Products _
    Join det In db.OrderDetails _
    On New With {ord.OrderID, prod.ProductID} Equals _
    New With {det.OrderID, det.ProductID} _
    Select ord.OrderID, prod.ProductID, det.UnitPrice
        var query =
from ord in db.Orders
from prod in db.Products
join det in db.OrderDetails
    on new { ord.OrderID, prod.ProductID } equals new { det.OrderID, det.ProductID }
    into details
from det in details
select new { ord.OrderID, prod.ProductID, det.UnitPrice };

請參閱

其他資源

LINQ to SQL 的查詢概念