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?
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.
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.
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.
For LINQ to Objects, it's a stable quicksort that is used.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With