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.
Note
LINQ to SQL does not support the Last operator.
Example
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.
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);
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.
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);
See Also
Concepts
Downloading Sample Databases (LINQ to SQL)