Queryable.ThenByDescending Метод

Определение

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

Перегрузки

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

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

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

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

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

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

public:
generic <typename TSource, typename TKey>
[System::Runtime::CompilerServices::Extension]
 static System::Linq::IOrderedQueryable<TSource> ^ ThenByDescending(System::Linq::IOrderedQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, TKey> ^> ^ keySelector);
public static System.Linq.IOrderedQueryable<TSource> ThenByDescending<TSource,TKey> (this System.Linq.IOrderedQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,TKey>> keySelector);
static member ThenByDescending : System.Linq.IOrderedQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, 'Key>> -> System.Linq.IOrderedQueryable<'Source>
<Extension()>
Public Function ThenByDescending(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.

Комментарии

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

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

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

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

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

Коллекция, элементы которой отсортированы по ключу в порядке убывания.

Исключения

Параметр source, keySelector или comparer имеет значение null.

Примеры

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

public class CaseInsensitiveComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        return string.Compare(x, y, true);
    }
}

public static void ThenByDescendingEx1()
{
    string[] fruits =
    { "apPLe", "baNanA", "apple", "APple", "orange", "BAnana", "ORANGE", "apPLE" };

    // Sort the strings first ascending by their length and
    // then descending using a custom case insensitive comparer.
    IEnumerable<string> query =
        fruits.AsQueryable()
        .OrderBy(fruit => fruit.Length)
        .ThenByDescending(fruit => fruit, new CaseInsensitiveComparer());

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

/*
    This code produces the following output:

    apPLe
    apple
    APple
    apPLE
    orange
    ORANGE
    baNanA
    BAnana
*/
Class CaseInsensitiveComparer
    Implements IComparer(Of String)

    Function Compare(ByVal x As String, ByVal y As String) As Integer _
        Implements IComparer(Of String).Compare

        ' Compare values and ignore case.
        Return String.Compare(x, y, True)
    End Function
End Class

Sub ThenByDescendingEx1()
    Dim fruits() As String = _
        {"apPLe", "baNanA", "apple", "APple", "orange", "BAnana", "ORANGE", "apPLE"}

    ' Sort the strings first ascending by their length and 
    ' then descending by using a custom case insensitive comparer.
    Dim query = fruits.AsQueryable() _
        .OrderBy(Function(fruit) fruit.Length) _
        .ThenByDescending(Function(fruit) fruit, New CaseInsensitiveComparer())

    Dim output As New System.Text.StringBuilder
    For Each fruit As String In query
        output.AppendLine(fruit)
    Next

    ' Display the results.
    MsgBox(output.ToString())
End Sub

' This code produces the following output:

' apPLe
' apple
' APple
' apPLE
' orange
' ORANGE
' baNanA
' BAnana

Комментарии

Этот метод имеет по крайней мере один параметр типа 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 используется для сравнения значений ключей.

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