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
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);
I was trying to also sort by a DateTime field descending and this seems to do the trick:
var ud = (from d in env
orderby -d.ReportDate.Ticks
select d.ReportDate.ToString("yyyy-MMM") ).Distinct();
env.OrderByDescending(x => x.ReportDate)
This statement will definitely help you:
env = env.OrderByDescending(c => c.ReportDate).ToList();