Compartilhar via


Exemplos de sintaxe da expressão de consulta: Classificação

Os exemplos neste tópico demonstram como usar os métodos OrderBy e OrderByDescending para consultar o Modelo de Vendas do AdventureWorks usando a sintaxe de expressão de consulta. O Modelo de vendas AdventureWorks usado nesses exemplos é criado a partir das tabelas Contact, Address, Product, SalesOrderHeader e SalesOrderDetail no banco de dados de exemplo AdventureWorks.

Os exemplos deste tópico usam as seguintes instruções using/Imports:

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Globalization;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Data.Common;

Option Explicit On
Option Strict On
Imports System.Data.Objects
Imports System.Globalization

OrderBy

Exemplo

O exemplo a seguir usa OrderBy para retornar uma lista de contatos ordenados por sobrenome.

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    IQueryable<Contact> sortedNames =
        from n in context.Contacts
        orderby n.LastName
        select n;

    Console.WriteLine("The sorted list of last names:");
    foreach (Contact n in sortedNames)
    {
        Console.WriteLine(n.LastName);
    }
}
Using context As New AdventureWorksEntities
    Dim contacts As ObjectSet(Of Contact) = context.Contacts

    Dim sortedContacts = _
        From contact In contacts _
        Order By contact.LastName _
        Select contact

    Console.WriteLine("The sorted list of last names:")
    For Each n As Contact In sortedContacts
        Console.WriteLine(n.LastName)
    Next
End Using

Exemplo

O exemplo a seguir usa OrderBy para classificar uma lista de contatos pelo comprimento do sobrenome.

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    IQueryable<Contact> sortedNames =
        from n in context.Contacts
        orderby n.LastName.Length
        select n;

    Console.WriteLine("The sorted list of last names (by length):");
    foreach (Contact n in sortedNames)
    {
        Console.WriteLine(n.LastName);
    }
}
Using context As New AdventureWorksEntities
    Dim contacts As ObjectSet(Of Contact) = context.Contacts

    Dim sortedNames = _
        From n In contacts _
        Order By n.LastName.Length _
        Select n

    Console.WriteLine("The sorted list of last names (by length):")
    For Each n As Contact In sortedNames
        Console.WriteLine(n.LastName)
    Next
End Using

OrderByDescending

Exemplo

O exemplo a seguir usa orderby… descending (Order By … Descending no Visual Basic), que é equivalente ao método de OrderByDescending , para classificar a tabela de preços de mais alto para o menor.

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    IQueryable<Decimal> sortedPrices =
        from p in context.Products
        orderby p.ListPrice descending
        select p.ListPrice;

    Console.WriteLine("The list price from highest to lowest:");
    foreach (Decimal price in sortedPrices)
    {
        Console.WriteLine(price);
    }
}
Using context As New AdventureWorksEntities
    Dim products As ObjectSet(Of Product) = context.Products

    Dim sortedPrices = _
        From product In products _
        Order By product.ListPrice Descending _
        Select product.ListPrice

    Console.WriteLine("The list price from highest to lowest:")
    For Each price As Decimal In sortedPrices
        Console.WriteLine(price)
    Next
End Using

ThenBy

Exemplo

O exemplo a seguir usa OrderBy e ThenBy para retornar uma lista de contatos ordenados por sobrenome e em seguida pelo nome.

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    IQueryable<Contact> sortedContacts =
        from contact in context.Contacts
        orderby contact.LastName, contact.FirstName
        select contact;

    Console.WriteLine("The list of contacts sorted by last name then by first name:");
    foreach (Contact sortedContact in sortedContacts)
    {
        Console.WriteLine(sortedContact.LastName + ", " + sortedContact.FirstName);
    }
}
Using context As New AdventureWorksEntities
    Dim contacts As ObjectSet(Of Contact) = context.Contacts

    Dim sortedContacts = _
        From contact In contacts _
        Order By contact.LastName, contact.FirstName _
        Select contact

    Console.WriteLine("The list of contacts sorted by last name then by first name:")
    For Each sortedContact As Contact In sortedContacts
        Console.WriteLine(sortedContact.LastName + ", " + sortedContact.FirstName)
    Next
End Using

ThenByDescending

Exemplo

O exemplo a seguir usa OrderBy… Descending, que é equivalente ao método de ThenByDescending , para classificar uma lista de produtos, principalmente por nome e em seguida pelo custo da tabela de mais alto para o menor.

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    IQueryable<Product> query =
        from product in context.Products
        orderby product.Name, product.ListPrice descending
        select product;

    foreach (Product product in query)
    {
        Console.WriteLine("Product ID: {0} Product Name: {1} List Price {2}",
            product.ProductID,
            product.Name,
            product.ListPrice);
    }
}
Using context As New AdventureWorksEntities
    Dim products As ObjectSet(Of Product) = context.Products

    Dim query As IQueryable(Of Product) = _
        From product In products _
        Order By product.Name, product.ListPrice Descending _
        Select product

    For Each prod As Product In query
        Console.WriteLine("Product ID: {0} Product Name: {1} List Price {2}", _
            prod.ProductID, _
            prod.Name, _
            prod.ListPrice)
    Next
End Using

Confira também