Accepted answer

You shouldn't to try order the date as string;

var res = objUI.Where(x => x.LastLogin != null)
    .GroupBy(x => x.LastLogin.Value.Date)
    .OrderByDescending(x => x.Key)
    .Select(x => new { LastLogin = string.Format("{0:MM/dd/yyyy}", x.Key) })


You're ordering by your string representation which starts with the month.

It looks like you're actually only interested in distinct dates though - grouping and then discarding everything other than the key is equivalent to just projecting and then taking distinct data. I'd also suggest avoiding an anonymous type unless you really need it - an anonymous type with only a single property is usually a bad idea.

Finally, if you're formatting a single value - certainly a DateTime value - it's simpler to just call the ToString method. In the code below I've explicitly specified the invariant culture too - otherwise you may find an unexpected calendar system is used...

So I'd write:

var res = objUI.Where(x => x.LastLogin != null)
               .Select(x => x.LastLogin)
               .OrderByDescending(x => x)
               .Select(x => x.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture))

Related Articles