orderby (Cláusula, Referencia de C#)orderby clause (C# Reference)

En una expresión de consulta, la cláusula orderby hace que la secuencia o subsecuencia (grupo) devuelta se ordene de forma ascendente o descendente.In a query expression, the orderby clause causes the returned sequence or subsequence (group) to be sorted in either ascending or descending order. Se pueden especificar varias claves para llevar a cabo una o varias operaciones de ordenación secundaria.Multiple keys can be specified in order to perform one or more secondary sort operations. La ordenación se realiza mediante el comparador predeterminado del tipo de elemento.The sorting is performed by the default comparer for the type of the element. El criterio de ordenación predeterminado es el ascendente.The default sort order is ascending. También puede especificar un comparador personalizado.You can also specify a custom comparer. En cambio, solo está disponible mediante la sintaxis basada en métodos.However, it is only available by using method-based syntax. Para obtener más información, consulte Sorting Data (Ordenación de datos).For more information, see Sorting Data.

EjemploExample

En el ejemplo siguiente, la primera consulta ordena las palabras en orden alfabético a partir de la A y la segunda consulta ordena las mismas palabras en orden descendente.In the following example, the first query sorts the words in alphabetical order starting from A, and second query sorts the same words in descending order. (La palabra clave ascending es el valor de ordenación predeterminado y puede omitirse).(The ascending keyword is the default sort value and can be omitted.)

class OrderbySample1
{
    static void Main()
    {            
        // Create a delicious data source.
        string[] fruits = { "cherry", "apple", "blueberry" };

        // Query for ascending sort.
        IEnumerable<string> sortAscendingQuery =
            from fruit in fruits
            orderby fruit //"ascending" is default
            select fruit;

        // Query for descending sort.
        IEnumerable<string> sortDescendingQuery =
            from w in fruits
            orderby w descending
            select w;            

        // Execute the query.
        Console.WriteLine("Ascending:");
        foreach (string s in sortAscendingQuery)
        {
            Console.WriteLine(s);
        }

        // Execute the query.
        Console.WriteLine(Environment.NewLine + "Descending:");
        foreach (string s in sortDescendingQuery)
        {
            Console.WriteLine(s);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
Ascending:
apple
blueberry
cherry

Descending:
cherry
blueberry
apple
*/

EjemploExample

En el ejemplo siguiente, se realiza una ordenación primaria por apellidos de los alumnos y, después, una ordenación secundaria por sus nombres.The following example performs a primary sort on the students' last names, and then a secondary sort on their first names.

class OrderbySample2
{
    // The element type of the data source.
    public class Student
    {
        public string First { get; set; }
        public string Last { get; set; }
        public int ID { get; set; }
    }

    public static List<Student> GetStudents()
    {
        // Use a collection initializer to create the data source. Note that each element
        //  in the list contains an inner sequence of scores.
        List<Student> students = new List<Student>
        {
           new Student {First="Svetlana", Last="Omelchenko", ID=111},
           new Student {First="Claire", Last="O'Donnell", ID=112},
           new Student {First="Sven", Last="Mortensen", ID=113},
           new Student {First="Cesar", Last="Garcia", ID=114},
           new Student {First="Debra", Last="Garcia", ID=115} 
        };

        return students;

    }
    static void Main(string[] args)
    {
        // Create the data source.
        List<Student> students = GetStudents();
        
        // Create the query.
        IEnumerable<Student> sortedStudents =
            from student in students
            orderby student.Last ascending, student.First ascending
            select student;

        // Execute the query.
        Console.WriteLine("sortedStudents:");
        foreach (Student student in sortedStudents)
            Console.WriteLine(student.Last + " " + student.First);           

        // Now create groups and sort the groups. The query first sorts the names
        // of all students so that they will be in alphabetical order after they are
        // grouped. The second orderby sorts the group keys in alpha order.            
        var sortedGroups =
            from student in students
            orderby student.Last, student.First
            group student by student.Last[0] into newGroup
            orderby newGroup.Key
            select newGroup;

        // Execute the query.
        Console.WriteLine(Environment.NewLine + "sortedGroups:");
        foreach (var studentGroup in sortedGroups)
        {
            Console.WriteLine(studentGroup.Key);
            foreach (var student in studentGroup)
            {
                Console.WriteLine("   {0}, {1}", student.Last, student.First);
            }
        }

        // Keep the console window open in debug mode
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:  
sortedStudents:
Garcia Cesar
Garcia Debra
Mortensen Sven
O'Donnell Claire
Omelchenko Svetlana

sortedGroups:
G
   Garcia, Cesar
   Garcia, Debra
M
   Mortensen, Sven
O
   O'Donnell, Claire
   Omelchenko, Svetlana
*/

ComentariosRemarks

En tiempo de compilación, la cláusula orderby se convierte en una llamada al método OrderBy.At compile time, the orderby clause is translated to a call to the OrderBy method. Varias claves en la cláusula orderby se convierten en llamadas al método ThenBy.Multiple keys in the orderby clause translate to ThenBy method calls.

Vea tambiénSee also