Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Orderby Descending Query

I'm sure this will be a relatively simple one.

I have a LINQ query that I want to order by the most recently created date.

See:

        var itemList = from t in ctn.Items                         where !t.Items && t.DeliverySelection                         orderby t.Delivery.SubmissionDate descending                         select t; 

I have also tried:

       var itemList = (from t in ctn.Items                         where !t.Items && t.DeliverySelection                         select t).OrderByDescending(); 

but this gives an error :

No overload for method 'OrderByDescending' takes 0 arguments

From what I've read, I'm fairly sure the first way I've done it should work. I've tried changing descending to ascending just to see if it does anything but it stays the same.

I'd be grateful if someone could take a look at the query and see if I'm doing anything wrong. Thanks :)

like image 253
109221793 Avatar asked Mar 17 '11 20:03

109221793


People also ask

How do I get data in descending order in LINQ?

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.

How do you do OrderBy in LINQ?

LINQ includes five sorting operators: OrderBy, OrderByDescending, ThenBy, ThenByDescending and Reverse. LINQ query syntax does not support OrderByDescending, ThenBy, ThenByDescending and Reverse. It only supports 'Order By' clause with 'ascending' and 'descending' sorting direction.

What is OrderByDescending?

OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) Sorts the elements of a sequence in descending order according to a key.

How does OrderBy work in C#?

In a query expression, the orderby clause causes the returned sequence or subsequence (group) to be sorted in either ascending or descending order. Multiple keys can be specified in order to perform one or more secondary sort operations. The sorting is performed by the default comparer for the type of the element.


1 Answers

You need to choose a Property to sort by and pass it as a lambda expression to OrderByDescending

like:

.OrderByDescending(x => x.Delivery.SubmissionDate); 

Really, though the first version of your LINQ statement should work. Is t.Delivery.SubmissionDate actually populated with valid dates?

like image 70
Adam Price Avatar answered Oct 01 '22 11:10

Adam Price