使用First運算符傳回序列中的第一個元素。 使用 First 的查詢會立即執行。
備註
LINQ to SQL 不支援 Last 運算子。
範例 1
下列程式碼會在資料表中尋找第一個 Shipper:
如果您針對 Northwind 範例資料庫執行此查詢,結果會是
ID = 1, Company = Speedy Express。
Shipper shipper = db.Shippers.First();
Console.WriteLine("ID = {0}, Company = {1}", shipper.ShipperID,
shipper.CompanyName);
Dim shipper As Shipper = db.Shippers.First()
Console.WriteLine("ID = {0}, Company = {1}", shipper.ShipperID, _
shipper.CompanyName)
範例 2
下列程式碼會尋找具有 BONAP 的單一CustomerCustomerID。
如果您針對 Northwind 範例資料庫執行此查詢,則結果為 ID = BONAP, Contact = Laurence Lebihan。
Customer custQuery =
(from custs in db.Customers
where custs.CustomerID == "BONAP"
select custs)
.First();
Console.WriteLine("ID = {0}, Contact = {1}", custQuery.CustomerID,
custQuery.ContactName);
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)