如何在下面的代碼中更改LINQ查詢以按降序排序(最新的第一個,最早的最後一個)?LINQ orderby on date字段降序
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
雖然問題被標記爲「linq-to-entities」,代碼使用'Enumerable',其中'Distinct()'保持順序。在Distinct()之後進行排序以減少需要排序的結果的大小並且與其中'Distinct()'確實不能保證順序的其他linq提供者兼容仍然是一個好主意 – 2017-10-19 13:17:00