LINQ orderby on date field in descending order

前端 未结 4 503
广开言路
广开言路 2020-12-24 06:18

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 S         


        
4条回答
  •  失恋的感觉
    2020-12-24 06:30

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

提交回复
热议问题