Enumerable.OrderBy Método
Definición
Ordena de manera ascendente los elementos de una secuencia.Sorts the elements of a sequence in ascending order.
Sobrecargas
OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) |
Ordena de manera ascendente los elementos de una secuencia en función de una clave.Sorts the elements of a sequence in ascending order according to a key. |
OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>) |
Ordena de manera ascendente los elementos de una secuencia utilizando un comparador especificado.Sorts the elements of a sequence in ascending order by using a specified comparer. |
OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)
Ordena de manera ascendente los elementos de una secuencia en función de una clave.Sorts the elements of a sequence in ascending order according to a key.
public:
generic <typename TSource, typename TKey>
[System::Runtime::CompilerServices::Extension]
static System::Linq::IOrderedEnumerable<TSource> ^ OrderBy(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, TKey> ^ keySelector);
public static System.Linq.IOrderedEnumerable<TSource> OrderBy<TSource,TKey> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,TKey> keySelector);
static member OrderBy : seq<'Source> * Func<'Source, 'Key> -> System.Linq.IOrderedEnumerable<'Source>
<Extension()>
Public Function OrderBy(Of TSource, TKey) (source As IEnumerable(Of TSource), keySelector As Func(Of TSource, TKey)) As IOrderedEnumerable(Of TSource)
Parámetros de tipo
- TSource
Tipo de los elementos de source
.The type of the elements of source
.
- TKey
Tipo de la clave devuelta por keySelector
.The type of the key returned by keySelector
.
Parámetros
- source
- IEnumerable<TSource>
Secuencia de valores que se va a ordenar.A sequence of values to order.
- keySelector
- Func<TSource,TKey>
Función para extraer una clave a partir de un elemento.A function to extract a key from an element.
Devoluciones
- IOrderedEnumerable<TSource>
Una interfaz IOrderedEnumerable<TElement> cuyos elementos se ordenan con arreglo a una clave.An IOrderedEnumerable<TElement> whose elements are sorted according to a key.
Excepciones
source
o keySelector
es null
.source
or keySelector
is null
.
Ejemplos
En el ejemplo de código siguiente se muestra cómo usar OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) para ordenar los elementos de una secuencia.The following code example demonstrates how to use OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) to sort the elements of a sequence.
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void OrderByEx1()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
IEnumerable<Pet> query = pets.OrderBy(pet => pet.Age);
foreach (Pet pet in query)
{
Console.WriteLine("{0} - {1}", pet.Name, pet.Age);
}
}
/*
This code produces the following output:
Whiskers - 1
Boots - 4
Barley - 8
*/
Structure Pet
Public Name As String
Public Age As Integer
End Structure
Sub OrderByEx1()
' Create an array of Pet objects.
Dim pets() As Pet = {New Pet With {.Name = "Barley", .Age = 8},
New Pet With {.Name = "Boots", .Age = 4},
New Pet With {.Name = "Whiskers", .Age = 1}}
' Order the Pet objects by their Age property.
Dim query As IEnumerable(Of Pet) =
pets.OrderBy(Function(pet) pet.Age)
Dim output As New System.Text.StringBuilder
For Each pt As Pet In query
output.AppendLine(pt.Name & " - " & pt.Age)
Next
' Display the output.
Console.WriteLine(output.ToString())
End Sub
' This code produces the following output:
'
' Whiskers - 1
' Boots - 4
' Barley - 8
Comentarios
Este método se implementa mediante la ejecución aplazada.This method is implemented by using deferred execution. El valor devuelto inmediato es un objeto que almacena toda la información necesaria para realizar la acción.The immediate return value is an object that stores all the information that is required to perform the action. La consulta representada por este método no se ejecuta hasta que el objeto se enumera mediante una llamada a su GetEnumerator
método directamente o mediante foreach
en Visual C# o For Each
en Visual Basic.The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator
method directly or by using foreach
in Visual C# or For Each
in Visual Basic.
Para ordenar una secuencia por los valores de los propios elementos, especifique la función de identidad ( x => x
en Visual C# o Function(x) x
en Visual Basic) para keySelector
.To order a sequence by the values of the elements themselves, specify the identity function (x => x
in Visual C# or Function(x) x
in Visual Basic) for keySelector
.
Se definen dos métodos para extender el tipo IOrderedEnumerable<TElement> , que es el tipo de valor devuelto de este método.Two methods are defined to extend the type IOrderedEnumerable<TElement>, which is the return type of this method. Estos dos métodos, a decir, ThenBy
y ThenByDescending
, permiten especificar criterios de ordenación adicionales para ordenar una secuencia.These two methods, namely ThenBy
and ThenByDescending
, enable you to specify additional sort criteria to sort a sequence. ThenBy
y ThenByDescending
también devuelven IOrderedEnumerable<TElement> , lo que significa que ThenBy
se puede realizar cualquier número de llamadas consecutivas a o ThenByDescending
.ThenBy
and ThenByDescending
also return an IOrderedEnumerable<TElement>, which means any number of consecutive calls to ThenBy
or ThenByDescending
can be made.
Nota
Dado IOrderedEnumerable<TElement> que hereda de IEnumerable<T> , puede llamar OrderBy a o a OrderByDescending los resultados de una llamada a OrderBy , OrderByDescending ThenBy o ThenByDescending .Because IOrderedEnumerable<TElement> inherits from IEnumerable<T>, you can call OrderBy or OrderByDescending on the results of a call to OrderBy, OrderByDescending, ThenBy or ThenByDescending. Al hacerlo, se introduce una nueva ordenación principal que omite la ordenación previamente establecida.Doing this introduces a new primary ordering that ignores the previously established ordering.
Este método compara las claves mediante el comparador predeterminado Default .This method compares keys by using the default comparer Default.
Este método realiza una ordenación estable; es decir, si las claves de dos elementos son iguales, se conserva el orden de los elementos.This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved. Por el contrario, una ordenación inestable no conserva el orden de los elementos que tienen la misma clave.In contrast, an unstable sort does not preserve the order of elements that have the same key.
En la sintaxis de las expresiones de consulta, una orderby
cláusula (Visual C#) o Order By
(Visual Basic) se traduce en una invocación de OrderBy .In query expression syntax, an orderby
(Visual C#) or Order By
(Visual Basic) clause translates to an invocation of OrderBy.
Consulte también
- OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)
- OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>)
- orderby (Cláusula, Referencia de C#)orderby clause (C# Reference)
- Order By (Cláusula, Visual Basic)Order By Clause (Visual Basic)
Se aplica a
OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>)
Ordena de manera ascendente los elementos de una secuencia utilizando un comparador especificado.Sorts the elements of a sequence in ascending order by using a specified comparer.
public:
generic <typename TSource, typename TKey>
[System::Runtime::CompilerServices::Extension]
static System::Linq::IOrderedEnumerable<TSource> ^ OrderBy(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, TKey> ^ keySelector, System::Collections::Generic::IComparer<TKey> ^ comparer);
public static System.Linq.IOrderedEnumerable<TSource> OrderBy<TSource,TKey> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,TKey> keySelector, System.Collections.Generic.IComparer<TKey> comparer);
public static System.Linq.IOrderedEnumerable<TSource> OrderBy<TSource,TKey> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,TKey> keySelector, System.Collections.Generic.IComparer<TKey>? comparer);
static member OrderBy : seq<'Source> * Func<'Source, 'Key> * System.Collections.Generic.IComparer<'Key> -> System.Linq.IOrderedEnumerable<'Source>
<Extension()>
Public Function OrderBy(Of TSource, TKey) (source As IEnumerable(Of TSource), keySelector As Func(Of TSource, TKey), comparer As IComparer(Of TKey)) As IOrderedEnumerable(Of TSource)
Parámetros de tipo
- TSource
Tipo de los elementos de source
.The type of the elements of source
.
- TKey
Tipo de la clave devuelta por keySelector
.The type of the key returned by keySelector
.
Parámetros
- source
- IEnumerable<TSource>
Secuencia de valores que se va a ordenar.A sequence of values to order.
- keySelector
- Func<TSource,TKey>
Función para extraer una clave a partir de un elemento.A function to extract a key from an element.
- comparer
- IComparer<TKey>
IComparer<T> para comparar claves.An IComparer<T> to compare keys.
Devoluciones
- IOrderedEnumerable<TSource>
Una interfaz IOrderedEnumerable<TElement> cuyos elementos se ordenan con arreglo a una clave.An IOrderedEnumerable<TElement> whose elements are sorted according to a key.
Excepciones
source
o keySelector
es null
.source
or keySelector
is null
.
Comentarios
Este método se implementa mediante la ejecución aplazada.This method is implemented by using deferred execution. El valor devuelto inmediato es un objeto que almacena toda la información necesaria para realizar la acción.The immediate return value is an object that stores all the information that is required to perform the action. La consulta representada por este método no se ejecuta hasta que el objeto se enumera mediante una llamada a su GetEnumerator
método directamente o mediante foreach
en Visual C# o For Each
en Visual Basic.The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator
method directly or by using foreach
in Visual C# or For Each
in Visual Basic.
Para ordenar una secuencia por los valores de los propios elementos, especifique la función de identidad ( x => x
en Visual C# o Function(x) x
en Visual Basic) para keySelector
.To order a sequence by the values of the elements themselves, specify the identity function (x => x
in Visual C# or Function(x) x
in Visual Basic) for keySelector
.
Se definen dos métodos para extender el tipo IOrderedEnumerable<TElement> , que es el tipo de valor devuelto de este método.Two methods are defined to extend the type IOrderedEnumerable<TElement>, which is the return type of this method. Estos dos métodos, a decir, ThenBy
y ThenByDescending
, permiten especificar criterios de ordenación adicionales para ordenar una secuencia.These two methods, namely ThenBy
and ThenByDescending
, enable you to specify additional sort criteria to sort a sequence. ThenBy
y ThenByDescending
también devuelven IOrderedEnumerable<TElement> , lo que significa que ThenBy
se puede realizar cualquier número de llamadas consecutivas a o ThenByDescending
.ThenBy
and ThenByDescending
also return an IOrderedEnumerable<TElement>, which means any number of consecutive calls to ThenBy
or ThenByDescending
can be made.
Nota
Dado IOrderedEnumerable<TElement> que hereda de IEnumerable<T> , puede llamar OrderBy a o a OrderByDescending los resultados de una llamada a OrderBy , OrderByDescending ThenBy o ThenByDescending .Because IOrderedEnumerable<TElement> inherits from IEnumerable<T>, you can call OrderBy or OrderByDescending on the results of a call to OrderBy, OrderByDescending, ThenBy or ThenByDescending. Al hacerlo, se introduce una nueva ordenación principal que omite la ordenación previamente establecida.Doing this introduces a new primary ordering that ignores the previously established ordering.
Si comparer
es null
, se utiliza el comparador predeterminado Default para comparar las claves.If comparer
is null
, the default comparer Default is used to compare keys.
Este método realiza una ordenación estable; es decir, si las claves de dos elementos son iguales, se conserva el orden de los elementos.This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved. Por el contrario, una ordenación inestable no conserva el orden de los elementos que tienen la misma clave.In contrast, an unstable sort does not preserve the order of elements that have the same key.
Consulte también
- OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)
- OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>)