Поделиться через


Queryable.ThenBy Метод

Определение

Выполняет последующее упорядочение элементов в последовательности в порядке возрастания.

Перегрузки

Имя Описание
ThenBy<TSource,TKey>(IOrderedQueryable<TSource>, Expression<Func<TSource,TKey>>, IComparer<TKey>)

Выполняет последующее упорядочение элементов последовательности в порядке возрастания с помощью указанного средства сравнения.

ThenBy<TSource,TKey>(IOrderedQueryable<TSource>, Expression<Func<TSource,TKey>>)

Выполняет последующее упорядочение элементов последовательности в порядке возрастания в соответствии с ключом.

ThenBy<TSource,TKey>(IOrderedQueryable<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> ^ ThenBy(System::Linq::IOrderedQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, TKey> ^> ^ keySelector, System::Collections::Generic::IComparer<TKey> ^ comparer);
public static System.Linq.IOrderedQueryable<TSource> ThenBy<TSource,TKey>(this System.Linq.IOrderedQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,TKey>> keySelector, System.Collections.Generic.IComparer<TKey> comparer);
public static System.Linq.IOrderedQueryable<TSource> ThenBy<TSource,TKey>(this System.Linq.IOrderedQueryable<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> ThenBy<TSource,TKey>(this System.Linq.IOrderedQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,TKey>> keySelector, System.Collections.Generic.IComparer<TKey>? comparer);
static member ThenBy : System.Linq.IOrderedQueryable<'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 ThenBy : System.Linq.IOrderedQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, 'Key>> * System.Collections.Generic.IComparer<'Key> -> System.Linq.IOrderedQueryable<'Source>
<Extension()>
Public Function ThenBy(Of TSource, TKey) (source As IOrderedQueryable(Of TSource), keySelector As Expression(Of Func(Of TSource, TKey)), comparer As IComparer(Of TKey)) As IOrderedQueryable(Of TSource)

Параметры типа

TSource

Тип элементов source.

TKey

Тип ключа, возвращаемого функцией, keySelectorпредставленной .

Параметры

source
IOrderedQueryable<TSource>

Объект, IOrderedQueryable<T> содержащий элементы для сортировки.

keySelector
Expression<Func<TSource,TKey>>

Функция для извлечения ключа из каждого элемента.

comparer
IComparer<TKey>

Сравнение IComparer<T> ключей.

Возвращаемое значение

Элементы IOrderedQueryable<T> , элементы которых отсортированы по ключу.

Атрибуты

Исключения

source или keySelectorcomparer есть null.

Комментарии

Этот метод имеет по крайней мере один параметр типа, аргумент типа Expression<TDelegate> которого является одним из Func<T,TResult> типов. Для этих параметров можно передать лямбда-выражение и скомпилировать его в Expression<TDelegate>лямбда-выражение.

Метод ThenBy<TSource,TKey>(IOrderedQueryable<TSource>, Expression<Func<TSource,TKey>>, IComparer<TKey>) создает объект MethodCallExpression , представляющий ThenBy<TSource,TKey>(IOrderedQueryable<TSource>, Expression<Func<TSource,TKey>>, IComparer<TKey>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionCreateQuery<TElement>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра. Результат вызова CreateQuery<TElement>(Expression) возвращается к типу IOrderedQueryable<T> и возвращается.

Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов ThenBy<TSource,TKey>(IOrderedQueryable<TSource>, Expression<Func<TSource,TKey>>, IComparer<TKey>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, что он выполняет вторичный вид элементов на основе ключа, полученного source путем вызова keySelector каждого элемента source. Сохраняются все ранее установленные заказы сортировки. Параметр comparer используется для сравнения значений ключей.

Применяется к

ThenBy<TSource,TKey>(IOrderedQueryable<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> ^ ThenBy(System::Linq::IOrderedQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, TKey> ^> ^ keySelector);
public static System.Linq.IOrderedQueryable<TSource> ThenBy<TSource,TKey>(this System.Linq.IOrderedQueryable<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> ThenBy<TSource,TKey>(this System.Linq.IOrderedQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,TKey>> keySelector);
static member ThenBy : System.Linq.IOrderedQueryable<'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 ThenBy : System.Linq.IOrderedQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, 'Key>> -> System.Linq.IOrderedQueryable<'Source>
<Extension()>
Public Function ThenBy(Of TSource, TKey) (source As IOrderedQueryable(Of TSource), keySelector As Expression(Of Func(Of TSource, TKey))) As IOrderedQueryable(Of TSource)

Параметры типа

TSource

Тип элементов source.

TKey

Тип ключа, возвращаемого функцией, keySelectorпредставленной .

Параметры

source
IOrderedQueryable<TSource>

Объект, IOrderedQueryable<T> содержащий элементы для сортировки.

keySelector
Expression<Func<TSource,TKey>>

Функция для извлечения ключа из каждого элемента.

Возвращаемое значение

Элементы IOrderedQueryable<T> , элементы которых отсортированы по ключу.

Атрибуты

Исключения

source или keySelector есть null.

Примеры

В следующем примере кода показано, как использовать ThenBy<TSource,TKey>(IOrderedQueryable<TSource>, Expression<Func<TSource,TKey>>) для выполнения вторичного упорядочения элементов в последовательности.

string[] fruits = { "grape", "passionfruit", "banana", "apple",
                      "orange", "raspberry", "mango", "blueberry" };

// Sort the strings first by their length and then
// alphabetically by passing the identity selector function.
IEnumerable<string> query =
    fruits.AsQueryable()
    .OrderBy(fruit => fruit.Length).ThenBy(fruit => fruit);

foreach (string fruit in query)
    Console.WriteLine(fruit);

/*
    This code produces the following output:

    apple
    grape
    mango
    banana
    orange
    blueberry
    raspberry
    passionfruit
*/
Dim fruits() As String = _
    {"grape", "passionfruit", "banana", "mango", _
     "orange", "raspberry", "apple", "blueberry"}

' Sort the strings first by their length and then 
' alphabetically by passing the identity selector function.
Dim query = fruits.AsQueryable() _
    .OrderBy(Function(fruit) fruit.Length).ThenBy(Function(fruit) fruit)

' Display the results.
Dim output As New System.Text.StringBuilder
For Each fruit As String In query
    output.AppendLine(fruit)
Next
MsgBox(output.ToString())

'This code produces the following output:

'apple
'grape
'mango
'banana
'orange
'blueberry
'raspberry
'passionfruit

Комментарии

Этот метод имеет по крайней мере один параметр типа, аргумент типа Expression<TDelegate> которого является одним из Func<T,TResult> типов. Для этих параметров можно передать лямбда-выражение и скомпилировать его в Expression<TDelegate>лямбда-выражение.

Метод ThenBy<TSource,TKey>(IOrderedQueryable<TSource>, Expression<Func<TSource,TKey>>) создает объект MethodCallExpression , представляющий ThenBy<TSource,TKey>(IOrderedQueryable<TSource>, Expression<Func<TSource,TKey>>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionCreateQuery<TElement>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра. Результат вызова CreateQuery<TElement>(Expression) возвращается к типу IOrderedQueryable<T> и возвращается.

Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов ThenBy<TSource,TKey>(IOrderedQueryable<TSource>, Expression<Func<TSource,TKey>>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, что он выполняет вторичный вид элементов на основе ключа, полученного source путем вызова keySelector каждого элемента source. Сохраняются все ранее установленные заказы сортировки.

Применяется к