LINQ orderby on日期字段按降序排列 [英] LINQ orderby on date field in descending order
本文介绍了LINQ orderby on日期字段按降序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何更改下面代码中的LINQ查询以按日期降序排列(最新,最早,最后)?
How can I change the LINQ query in the code below to sort by date in descending order (latest first, earliest last)?
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
我希望输出按以下顺序进行:
I want the output to in the following order:
may
april
march order
推荐答案
我认为Distinct()不能保证保持集合的顺序.
I don't believe that Distinct() is guaranteed to maintain the order of the set.
在转换为字符串之前,请先尝试提取匿名类型并对其进行区分/排序:
Try pulling out an anonymous type first and distinct/sort on that before you convert to string:
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 orderby on日期字段按降序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文