Coder Perfect

Orderby Descending Query in LINQ

Problem

I’m confident that this will be a simple task.

I’d like to sort a LINQ query 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’ve also attempted:

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

However, this results in the following error:

According to what I’ve read, the first method I tried should work. I tried switching from descending to ascending to see if it made a difference, but it didn’t.

I’d appreciate it if someone could glance over the query and see if there’s anything I’m missing. Thank you:)

Asked by 109221793

Solution #1

You must specify a Property to sort by and send it to OrderByDescending as a lambda expression.

like:

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

The first version of your LINQ statement, however, should work. Is t.Delivery t.Delivery t.Delivery t.Delive Is the SubmissionDate field filled with valid dates?

Answered by Adam Price

Solution #2

I believe the first failed because you are ordering a null value. If Delivery is a foreign key linked table, you should add it first, as seen in the following example:

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

Answered by mrosiak

Solution #3

The second one, in my opinion, should be

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

Answered by Jonathan

Solution #4

Simply to display it in a different format that I prefer for some reason: The first method returns an instance of your itemList as a System. Linq.IOrderedQueryable

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

That method is good, but if you wanted to put it straight into a List Object, you’d have to do the following:

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

To do so, simply append a.ToList() function to the end of the Query.

Something to keep in mind: I’m not sure if the!(not) expression is permitted in the Where() method off the top of my head.

Answered by nulltron

Post is based on https://stackoverflow.com/questions/5344805/linq-orderby-descending-query