【问题标题】:LINQ orderby on date field in descending orderLINQ orderby 按日期字段降序排列
【发布时间】:2011-04-28 04:00:25
【问题描述】:

如何更改下面代码中的 LINQ 查询以按日期降序排序(最新的在前,最早的在后)?

using System;
using System.Linq;
using System.Collections.Generic;


namespace Helloworld
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            List<Envelops> env = new List<Envelops> ();
            Envelops e = new Envelops { ReportDate = DateTime.Now };
            env.Add (e);
            e = new Envelops { ReportDate = DateTime.Now.AddDays (5) };
            env.Add (e);
            e = new Envelops { ReportDate = new DateTime (2011, 3, 3) };
            env.Add (e);
            e = new Envelops { ReportDate = DateTime.Now };
            env.Add (e);

            foreach (Envelops r in env) {
                Console.WriteLine (  r.ReportDate.ToString("yyyy-MMM"));
            }

            var ud = (from d in env                  
                select  d.ReportDate.ToString("yyyy-MMM") ).Distinct();     

            Console.WriteLine ("After distinct");

            foreach (var r in ud) {
                Console.WriteLine (r);
            }

        }
    }

    class Envelops
    {
        public DateTime ReportDate { get; set; }
    }

}`enter code here`

当前输出为:

2011-Apr
2011-May
2011-Mar
2011-Apr
After distinct
2011-Apr
2011-May
2011-Mar

我希望按以下顺序输出:

may
april
march order

【问题讨论】:

    标签: c# linq


    【解决方案1】:
    env.OrderByDescending(x => x.ReportDate)
    

    【讨论】:

      【解决方案2】:

      我不相信 Distinct() 可以保证保持集合的顺序。

      尝试在转换为字符串之前先提取一个匿名类型并对其进行区分/排序:

      var ud = env.Select(d => new 
                               {
                                   d.ReportDate.Year,
                                   d.ReportDate.Month,
                                   FormattedDate = d.ReportDate.ToString("yyyy-MMM")
                               })
                  .Distinct()
                  .OrderByDescending(d => d.Year)
                  .ThenByDescending(d => d.Month)
                  .Select(d => d.FormattedDate);
      

      【讨论】:

      • 虽然问题标记为linq-to-entities,但代码使用Enumerable,其中Distinct() 确实保持顺序。在Distinct() 之后进行排序仍然是一个好主意,以减少需要排序的结果的大小,并与Distinct() 确实不保证保留顺序的其他linq 提供程序兼容
      【解决方案3】:

      这句话肯定会对你有所帮助:

      env = env.OrderByDescending(c => c.ReportDate).ToList();
      

      【讨论】:

        【解决方案4】:

        我还尝试按 DateTime 字段降序排序,这似乎可以解决问题:

        var ud = (from d in env 
             orderby -d.ReportDate.Ticks                 
             select  d.ReportDate.ToString("yyyy-MMM") ).Distinct(); 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多