Editare

Partajați prin


Return the First Element in a Sequence

Use the First operator to return the first element in a sequence. Queries that use First are executed immediately.

Note

LINQ to SQL does not support the Last operator.

Example 1

The following code finds the first Shipper in a table:

If you run this query against the Northwind sample database, the results are

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)

Example 2

The following code finds the single Customer that has the CustomerID BONAP.

If you run this query against the Northwind sample database, the results are 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)

See also