Queryable.ThenBy Метод

Определение

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

Перегрузки

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

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

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

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

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

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

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);
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<TSource>

Объект 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>>) себя как созданный универсальный метод. Затем он передает MethodCallExpression CreateQuery<TElement>(Expression) метод, представленный IQueryProvider свойством Provider source параметра. Результат вызова CreateQuery<TElement>(Expression) приводится к типу IOrderedQueryable<T> и возвращается.

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

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

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

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

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);
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<TSource>

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

Исключения

Параметр source, keySelector или comparer имеет значение 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>) себя как созданный универсальный метод. Затем он передает MethodCallExpression CreateQuery<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 используется для сравнения значений ключей.

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