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开发者_如何学Go but it stays the same.
What am I doing wrong?
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?
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;
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);
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.
精彩评论