如何:返回序列中的第一个元素 (LINQ to SQL)
更新:November 2007
使用 First 运算符可返回序列中的第一个元素。使用 First 的查询是立即执行的。
说明: |
---|
LINQ to SQL 不支持 Last 运算符。 |
示例
下面的代码查找表中的第一个 Shipper:
如果您对 Northwind 示例数据库运行此查询,则结果为
ID = 1, Company = Speedy Express.
Dim shipper As Shipper = db.Shippers.First()
Console.WriteLine("ID = {0}, Company = {1}", shipper.ShipperID, _
shipper.CompanyName)
Shipper shipper = db.Shippers.First();
Console.WriteLine("ID = {0}, Company = {1}", shipper.ShipperID,
shipper.CompanyName);
下面的代码查找具有 CustomerID BONAP 的单个 Customer。
如果您对 Northwind 示例数据库运行此查询,则结果为 ID = BONAP, Contact = Laurence Lebihan。
Dim custquery As Customer = _
(From c In db.Customers _
Where c.CustomerID = "BONAP" _
Select c) _
.First()
Console.WriteLine("ID = {0}, Contact = {1}", custquery.CustomerID, _
custquery.ContactName)
Customer custQuery =
(from custs in db.Customers
where custs.CustomerID == "BONAP"
select custs)
.First();
Console.WriteLine("ID = {0}, Contact = {1}", custQuery.CustomerID,
custQuery.ContactName);