LINQ Orderby Descending Query

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

I tried:

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, the first way it should work. I've tried changing descending to ascending just to see if it does anything but it stays the same.

What am I doing wrong?

4 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?

1

I think this first failed because you are ordering value which is null. If Delivery is a foreign key associated table then you should include this table first, example below:

var itemList = from t in ctn.Items.Include(x=>x.Delivery) where !t.Items && t.DeliverySelection orderby t.Delivery.SubmissionDate descending select t; 
1

I think the second one should be

var itemList = (from t in ctn.Items where !t.Items && t.DeliverySelection select t).OrderByDescending(c => c.Delivery.SubmissionDate); 
1

Just to show it in a different format that I prefer to use for some reason: The first way returns your itemList as an System.Linq.IOrderedQueryable

using(var context = new ItemEntities()) { var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection) .OrderByDescending(x => x.Delivery.SubmissionDate); } 

That approach is fine, but if you wanted it straight into a List Object:

var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection) .OrderByDescending(x => x.Delivery.SubmissionDate).ToList(); 

All you have to do is append a .ToList() call to the end of the Query.

Something to note, off the top of my head I can't recall if the !(not) expression is acceptable in the Where() call.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like