How to: Return the First Element in a Sequence (LINQ to SQL)

How to: Return the First Element in a Sequence (LINQ to SQL)

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

NoteNote

LINQ to SQL does not support the Last operator.

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);


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);


Show:
© 2016 Microsoft