Condividi tramite


Restituire il primo elemento in una sequenza

Usare l'operatore First per restituire il primo elemento in una sequenza. Le query che usano First vengono eseguite immediatamente.

Annotazioni

LINQ to SQL non supporta l'operatore Last .

Esempio 1

Il codice seguente trova il primo Shipper in una tabella:

Se si esegue questa query sul database di esempio Northwind, i risultati sono

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)

Esempio 2

Il codice seguente trova il singolo Customer che ha il CustomerID BONAP.

Se si esegue questa query sul database di esempio Northwind, i risultati sono 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)

Vedere anche