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


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

Исходный код:
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> ^ 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);
[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> 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>
[<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 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<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>>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionCreateQuery<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>)

Исходный код:
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> ^ 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);
[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> 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>
[<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 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> ключей.

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

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

Атрибуты

Исключения

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

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