如何用LINQ订购物品

本文关键字:何用 LINQ | 更新日期: 2023-09-27 18:02:39

想法是。我有一些项目,最初我想通过DateCreated订购。

但是我有一些项目有LastDateTime。如果LastDateTime <DateTime。现在我需要在所有最新项目之后显示它们。所以他们必须在最后。>

所需输出结果示例:

#           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)

下面是我的linq查询的例子。它显示最后一天的所有项目<约会时间现在结束。但是它不能正确显示创建日期的顺序。>

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

如何用LINQ订购物品

尝试在您的最后一个orderbydescent中按DayID排序。

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

编辑:啊,抱歉没有看到。我最好的猜测是,因为您先按ID排序,这几乎会取消LastDate排序。你说你需要先在LastDate前订购,对吗?身份证的顺序有关系吗?如果不只是。orderbydescent (x => x. lastdate)