如何在下面的代码中更改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
答案 0 :(得分:65)
env.OrderByDescending(x => x.ReportDate)
答案 1 :(得分:42)
我不相信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);
答案 2 :(得分:3)
这句话肯定会对你有所帮助:
<!DOCTYPE html>
<html>
<head>
<title>Toggle-able input</title>
</head>
<body>
<input type="text" id="myFile">
<button onclick="myFunction()">Enable/disable</button>
</body>
答案 3 :(得分:0)
我试图按降序排列的DateTime字段进行排序,这似乎可以解决问题:
var ud = (from d in env
orderby -d.ReportDate.Ticks
select d.ReportDate.ToString("yyyy-MMM") ).Distinct();