分享方式:


傳回序列的第一個項目

使用 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

下列程式碼會尋找具有 Customer BONAP 的單一 CustomerID

如果您對 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)

另請參閱