PlainOldProgrammer
PlainOldProgrammer

Reputation: 2973

OrderByDescending vs OrderDescending LINQ Method in .NET 7+ Versions

.NET 7 introduced the OrderDescending LINQ method. I read the official documentation and didn't found why this was introduced if OrderByDescending method already exists. I noticed that both metods are implemented by using deferred execution, but I detected that the main difference is that OrderDescending doesn't have any signature that receives a Func, on the other hand, OrderByDescending method has it.

A simple code like this will give the same result:

int[] numbers = new int[] { 3, 5, 7, 8, 6, 9 };
var result1 = numbers.OrderDescending().ToList();          // 9, 8, 7, 6, 5, 3
var result2 = numbers.OrderByDescending(x => x).ToList();  // 9, 8, 7, 6, 5, 3

Both methods looks that they provide the same funcionality for this scenario. Since OrderDescending is the newest introduced method in LINQ, it looks simpler, and we can achieve same effect by passing a simple lambda expression to OrderByDescending like: OrderByDescending(x => x);.

Said that, what is the real purpose OrderDescending method has been introduced?

Upvotes: 4

Views: 137

Answers (2)

Guru Stron
Guru Stron

Reputation: 143098

Said that, what is the real purpose OrderDescending method has been introduced?

Both methods looks that they provide the same funcionality for this scenario. OrderDescending... looks simpler, ...

That's it, there is no hidden meaning or goal to the introduction of Order and OrderDescending methods other than providing a simpler way to write the identity sort for the collection (especially for the types having natural ordering).

It is equivalent to the OrderByDescending(x => x) but shorter (in theory it can have some optimizations, but have not investigated that).

See the proposal - [API Proposal]: Enumerable.Order and OrderDescending.

Also check out the current Enumerable.OrderDescending implementation accepting the IComparer<T> - in one of the branches it just directly calls OrderByDescending with the EnumerableSorter<T>.IdentityFunc:

public static IOrderedEnumerable<T> OrderDescending<T>(this IEnumerable<T> source, IComparer<T>? comparer) =>
    TypeIsImplicitlyStable<T>() && (comparer is null || comparer == Comparer<T>.Default) 
    ? new ImplicitlyStableOrderedIterator<T>(source, descending: true)
    : OrderByDescending(source, EnumerableSorter<T>.IdentityFunc, comparer);

Upvotes: 7

ramin firouzabadi
ramin firouzabadi

Reputation: 11

In summary, OrderDescending was introduced to provide a more straightforward and readable way to sort collections in descending order when no key selector is needed. It simplifies the code and aligns with the common use case of sorting elements directly, enhancing both the developer experience and code clarity.

Upvotes: 1

Related Questions