C# LINQ orderby on date字段降序排列
如何将下面代码中的LINQ查询更改为按日期降序排序(最晚的第一个,最早的最后一个) 我希望输出按以下顺序进行:C# LINQ orderby on date字段降序排列,c#,linq,C#,Linq,如何将下面代码中的LINQ查询更改为按日期降序排序(最晚的第一个,最早的最后一个) 我希望输出按以下顺序进行: may april march order env.OrderByDescending(x=>x.ReportDate) 我不相信Distinct()可以保证保持集合的顺序 在转换为字符串之前,请先尝试提取匿名类型并对其进行distinct/排序: var ud = env.Select(d => new {
may
april
march order
env.OrderByDescending(x=>x.ReportDate)
我不相信Distinct()可以保证保持集合的顺序
在转换为字符串之前,请先尝试提取匿名类型并对其进行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);
此声明肯定会帮助您:
env=env.OrderByDescending(c=>c.ReportDate.ToList();
我还试图按DateTime字段降序进行排序,这似乎达到了目的:
var ud = (from d in env
orderby -d.ReportDate.Ticks
select d.ReportDate.ToString("yyyy-MMM") ).Distinct();
当问题被标记为
linq to entities
时,代码使用的是Enumerable
,其中Distinct()
可以维持顺序。在Distinct()
之后进行排序仍然是一个好主意,以减少需要排序的结果的大小,并与其他linq提供程序兼容,因为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);
var ud = (from d in env
orderby -d.ReportDate.Ticks
select d.ReportDate.ToString("yyyy-MMM") ).Distinct();