Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq syntax for OrderBy with custom Comparer<T>

Tags:

There are two formats for any given Linq expression with a custom sort comparer:

Format 1

var query =     source     .Select(x => new { x.someProperty, x.otherProperty } )     .OrderBy(x => x, new myComparer()); 

Format 2

var query =     from x in source     orderby x // comparer expression goes here?     select new { x.someProperty, x.otherProperty }; 

Question:
What is the syntax for the order-by expression in the second format?

Not the question:
How to use a custom comparer as shown in the first format.

Bonus credit:
Are there actual, formal names for the two Linq formats listed above?

like image 501
Steve Konves Avatar asked Oct 05 '12 20:10

Steve Konves


People also ask

What is OrderBy in Linq?

LINQ OrderBy operator comes first in LINQ Sorting Operators. OrderBy operator sort the sequence (collection) based on particular property in ascending order. We can use OrderBy operator both in Query Syntax and Method Syntax.

What is difference between OrderBy and ThenBy in Linq?

The OrderBy() Method, first sort the elements of the sequence or collection in ascending order after that ThenBy() method is used to again sort the result of OrderBy() method in ascending order.

How do I get data in descending order in Linq?

OrderByDescending Operator If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.


1 Answers

What is the syntax for the order-by expression in the second format?

It doesn't exist. From the orderby clause documentation:

You can also specify a custom comparer. However, it is only available by using method-based syntax.


How to use a custom comparer in the first format.

You wrote it correctly. You can pass the IComparer<T> as you wrote.


Are there actual, formal names for the two Linq formats listed above?

Format 1 is called "Method-Based Syntax" (from previous link), and Format 2 is "Query Expression Syntax" (from here).

like image 122
Reed Copsey Avatar answered Oct 18 '22 22:10

Reed Copsey