如何:处理查询中的复合键
有些运算符只能带一个自变量。 如果您的参数必须包含数据库中的多个列,则您必须创建一个匿名类型来表示这种组合。
示例 1
下面的示例显示了调用 GroupBy
运算符的查询,此运算符只能带一个 key
自变量。
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);
}
}
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
示例 2
联接也属于这种情况,如下例中所示:
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 };
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