开发者

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();


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜