HOW TO:傳回序列中的第一個項目 (LINQ to SQL)
使用 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);