Queryable.OrderBy Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Сортирует элементы последовательности в порядке возрастания.
Перегрузки
| Имя | Описание |
|---|---|
| OrderBy<TSource,TKey>(IQueryable<TSource>, Expression<Func<TSource,TKey>>) |
Сортирует элементы последовательности в порядке возрастания в соответствии с ключом. |
| OrderBy<TSource,TKey>(IQueryable<TSource>, Expression<Func<TSource,TKey>>, IComparer<TKey>) |
Сортирует элементы последовательности в порядке возрастания с помощью указанного сравнения. |
OrderBy<TSource,TKey>(IQueryable<TSource>, Expression<Func<TSource,TKey>>)
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
Сортирует элементы последовательности в порядке возрастания в соответствии с ключом.
public:
generic <typename TSource, typename TKey>
[System::Runtime::CompilerServices::Extension]
static System::Linq::IOrderedQueryable<TSource> ^ OrderBy(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, TKey> ^> ^ keySelector);
public static System.Linq.IOrderedQueryable<TSource> OrderBy<TSource,TKey>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,TKey>> keySelector);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
public static System.Linq.IOrderedQueryable<TSource> OrderBy<TSource,TKey>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,TKey>> keySelector);
static member OrderBy : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, 'Key>> -> System.Linq.IOrderedQueryable<'Source>
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")>]
static member OrderBy : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, 'Key>> -> System.Linq.IOrderedQueryable<'Source>
<Extension()>
Public Function OrderBy(Of TSource, TKey) (source As IQueryable(Of TSource), keySelector As Expression(Of Func(Of TSource, TKey))) As IOrderedQueryable(Of TSource)
Параметры типа
- TSource
Тип элементов source.
- TKey
Тип ключа, возвращаемого функцией, представленной keySelector.
Параметры
- source
- IQueryable<TSource>
Последовательность значений для упорядочивания.
- keySelector
- Expression<Func<TSource,TKey>>
Функция для извлечения ключа из элемента.
Возвращаемое значение
Элементы IOrderedQueryable<T> , элементы которых отсортированы по ключу.
- Атрибуты
Исключения
source или keySelector есть null.
Примеры
В следующем примере кода показано, как сортировать OrderBy<TSource,TKey>(IQueryable<TSource>, Expression<Func<TSource,TKey>>) элементы последовательности.
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 } };
// Sort the Pet objects in the array by Pet.Age.
IEnumerable<Pet> query =
pets.AsQueryable().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
Shared Sub OrderByEx1()
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}}
' Sort the Pet objects in the array by Pet.Age.
Dim query As IEnumerable(Of Pet) = _
pets.AsQueryable().OrderBy(Function(pet) pet.Age)
Dim output As New System.Text.StringBuilder
For Each pet As Pet In query
output.AppendLine(String.Format("{0} - {1}", pet.Name, pet.Age))
Next
' Display the output.
MsgBox(output.ToString())
End Sub
' This code produces the following output:
' Whiskers - 1
' Boots - 4
' Barley - 8
Комментарии
Этот метод имеет по крайней мере один параметр типа, аргумент типа Expression<TDelegate> которого является одним из Func<T,TResult> типов. Для этих параметров можно передать лямбда-выражение и скомпилировать его в Expression<TDelegate>лямбда-выражение.
Метод OrderBy<TSource,TKey>(IQueryable<TSource>, Expression<Func<TSource,TKey>>) создает объект MethodCallExpression , представляющий OrderBy<TSource,TKey>(IQueryable<TSource>, Expression<Func<TSource,TKey>>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionCreateQuery<TElement>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра. Результат вызова CreateQuery<TElement>(Expression) возвращается к типу IOrderedQueryable<T> и возвращается.
Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов OrderBy<TSource,TKey>(IQueryable<TSource>, Expression<Func<TSource,TKey>>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, что он сортирует элементы на основе ключа, полученного source путем вызова keySelector каждого элемента source.
Применяется к
OrderBy<TSource,TKey>(IQueryable<TSource>, Expression<Func<TSource,TKey>>, IComparer<TKey>)
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
Сортирует элементы последовательности в порядке возрастания с помощью указанного сравнения.
public:
generic <typename TSource, typename TKey>
[System::Runtime::CompilerServices::Extension]
static System::Linq::IOrderedQueryable<TSource> ^ OrderBy(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, TKey> ^> ^ keySelector, System::Collections::Generic::IComparer<TKey> ^ comparer);
public static System.Linq.IOrderedQueryable<TSource> OrderBy<TSource,TKey>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,TKey>> keySelector, System.Collections.Generic.IComparer<TKey> comparer);
public static System.Linq.IOrderedQueryable<TSource> OrderBy<TSource,TKey>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,TKey>> keySelector, System.Collections.Generic.IComparer<TKey>? comparer);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
public static System.Linq.IOrderedQueryable<TSource> OrderBy<TSource,TKey>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,TKey>> keySelector, System.Collections.Generic.IComparer<TKey>? comparer);
static member OrderBy : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, 'Key>> * System.Collections.Generic.IComparer<'Key> -> System.Linq.IOrderedQueryable<'Source>
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")>]
static member OrderBy : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, 'Key>> * System.Collections.Generic.IComparer<'Key> -> System.Linq.IOrderedQueryable<'Source>
<Extension()>
Public Function OrderBy(Of TSource, TKey) (source As IQueryable(Of TSource), keySelector As Expression(Of Func(Of TSource, TKey)), comparer As IComparer(Of TKey)) As IOrderedQueryable(Of TSource)
Параметры типа
- TSource
Тип элементов source.
- TKey
Тип ключа, возвращаемого функцией, представленной keySelector.
Параметры
- source
- IQueryable<TSource>
Последовательность значений для упорядочивания.
- keySelector
- Expression<Func<TSource,TKey>>
Функция для извлечения ключа из элемента.
- comparer
- IComparer<TKey>
Сравнение IComparer<T> ключей.
Возвращаемое значение
Элементы IOrderedQueryable<T> , элементы которых отсортированы по ключу.
- Атрибуты
Исключения
source или keySelectorcomparer есть null.
Комментарии
Этот метод имеет по крайней мере один параметр типа, аргумент типа Expression<TDelegate> которого является одним из Func<T,TResult> типов. Для этих параметров можно передать лямбда-выражение и скомпилировать его в Expression<TDelegate>лямбда-выражение.
Метод OrderBy<TSource,TKey>(IQueryable<TSource>, Expression<Func<TSource,TKey>>, IComparer<TKey>) создает объект MethodCallExpression , представляющий OrderBy<TSource,TKey>(IQueryable<TSource>, Expression<Func<TSource,TKey>>, IComparer<TKey>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionCreateQuery<TElement>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра. Результат вызова CreateQuery<TElement>(Expression) возвращается к типу IOrderedQueryable<T> и возвращается.
Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов OrderBy<TSource,TKey>(IQueryable<TSource>, Expression<Func<TSource,TKey>>, IComparer<TKey>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, что он сортирует элементы на основе ключа, полученного source путем вызова keySelector каждого элемента source. Параметр comparer используется для сравнения ключей.