Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ orderby on date字段降序排列_C#_Linq - Fatal编程技术网

C# LINQ orderby on date字段降序排列

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 {

如何将下面代码中的LINQ查询更改为按日期降序排序(最晚的第一个,最早的最后一个)

我希望输出按以下顺序进行:

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();