Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ascending/descending in LINQ - can one change the order via parameter?

Tags:

c#

linq

I have a method which is given the parameter "bool sortAscending". Now I want to use LINQ to create sorted list depending on this parameter. I got then this:

var ascendingQuery = from data in dataList                       orderby data.Property ascending                       select data;  var descendingQuery = from data in dataList                       orderby data.Property descending                       select data; 

As you can see, both queries differ only in "ascending" resp. "descending". I'd like to merge both queries, but I don't know how. Does anyone have the answer?

like image 828
Johannes Avatar asked Dec 23 '08 11:12

Johannes


People also ask

How do I sort in LINQ descending order?

LINQ OrderBy Desc operator sorting the elements in descending order, it returns the collection in descending order. The values in the sequence of element returns the result in descending order based on the specific field. It is not valid in query syntax it is available only in the method syntax.

How do I use ascending order in LINQ?

In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order. We don't need to add any ascending condition in the query statement.

What is difference between OrderBy and ThenBy in LINQ?

Generally, ThenBy method is used with the OrderBy method. 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.

What sorting algorithm does LINQ use?

For LINQ to Objects, it's a stable quicksort that is used.


1 Answers

You can easily create your own extension method on IEnumerable or IQueryable:

public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource,TKey>     (this IEnumerable<TSource> source,      Func<TSource, TKey> keySelector,      bool descending) {     return descending ? source.OrderByDescending(keySelector)                       : source.OrderBy(keySelector); }  public static IOrderedQueryable<TSource> OrderByWithDirection<TSource,TKey>     (this IQueryable<TSource> source,      Expression<Func<TSource, TKey>> keySelector,      bool descending) {     return descending ? source.OrderByDescending(keySelector)                       : source.OrderBy(keySelector); } 

Yes, you lose the ability to use a query expression here - but frankly I don't think you're actually benefiting from a query expression anyway in this case. Query expressions are great for complex things, but if you're only doing a single operation it's simpler to just put that one operation:

var query = dataList.OrderByWithDirection(x => x.Property, direction); 
like image 113
Jon Skeet Avatar answered Nov 12 '22 17:11

Jon Skeet