LINQ orderby在日期字段中按降序排列
如何在下面的代码中更改LINQ查询,按日期降序排序(最新的,最早的,最后一个)?
using System; using System.Linq; using System.Collections.Generic; namespace Helloworld { class MainClass { public static void Main (string[] args) { List env = new List (); 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
我不相信Distinct()可以保证维持集合的顺序。
在转换为字符串之前,首先尝试拔出一个匿名类型并对其进行distinct / sort:
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);
env.OrderByDescending(x => x.ReportDate)
这句话肯定会帮助你:
env = env.OrderByDescending(c => c.ReportDate).ToList();