Michael Born
Michael Born

Reputation: 799

How to order items with LINQ?

The idea is. I have items which initially I would like to order by DateCreated. Last created shows first in a grid.

But I have some items which have LastDateTime. If LastDateTime < DateTime.Now I need to show them after all most current items. So they have to be at the end.

Example of needed output results:

#           Item                DateCreated                 LastDate
--------------------------------------------------------------------------
1.           Item 1             07-11-2011                   07-29-2011
2.           Item 2             07-10-2011                   07-29-2011
3.           Item 3             07-09-2011                   07-29-2011
4.           Item 4             07-08-2011                   07-29-2011
5.           Item 5             07-16-2011                   07-18-2011
6.           Item 6             07-13-2011                   07-15-2011
7.           Item 7             07-11-2011                   07-12-2011


Tables:
-------------------------------------------------

ID (PK)                Item (string)               DateCreated (DateTime)


Table 2
-------------------------------------------------

DayID (PK)             ID (FK)             DateTimeUtc (DateTime)

Here is example of my linq query. It shows all items with last day < date time now at the end. but it doesn't show properly order by created date.

return (from i in _entity.Items
        join d in _entity.Days 
        on i.ID equals d.ID into leftJoinTable
        where i.ID == 123

        select new 
        {  

          i.ID,
          i.Item,
          LastDate = leftJoinTable.OrderByDescending(a => a.DayID)
                                              .Select(a => a.DateTimeUtc)
                                              .FirstOrDefault()
        }).Distinct()
          .OrderByDescending(x => x.ID)
          .ThenBy(x=>x.LastDate)
          .ToList();

Upvotes: 1

Views: 962

Answers (1)

Gage
Gage

Reputation: 7513

Try ordering by DayID in your last OrderByDescending.

return (from i in _entity.Items
            join d in _entity.Days 
            on i.ID equals d.ID into leftJoinTable
            where i.ID == 123

            select new 
        {  
      i.ID,
      i.Item,
      LastDate = leftJoinTable.OrderByDescending(a => a.DayID)
                                          .Select(a => a.DateTimeUtc)
                                          .FirstOrDefault()
    }).Distinct()
      .OrderByDescending(x => x.ID) // You're ordering by ID first
      .ThenBy(x=>x.LastDate)
      .ToList();

EDIT: Ah sorry didn't see that. My best guess is that since your ordering by ID first which would almost cancel out the LastDate ordering. You said you need them ordered by LastDate first correct? Does it matter on the order of the ID's? If not just .OrderByDescending(x => x.LastDate)

Upvotes: 1

Related Questions