Condividi tramite


Procedura: restituire il primo elemento in una sequenza (LINQ to SQL)

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

NotaNota

LINQ to SQL non supporta l'operatore Last.

Esempio

Nel codice seguente viene cercato il primo Shipper in una tabella:

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

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

Nel codice seguente viene cercato il singolo Customer con CustomerID BONAP.

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

Vedere anche

Concetti

Download dei database di esempio (LINQ to SQL)

Altre risorse

Eseguire una query sugli esempi (LINQ to SQL)