orderByDescending date, month and year

I am using a linq query to get the data order by descending date. but when the year is chaged then descending order of date is not in proper way

Here is my code

in this code LastLogin is column with datetime datatype . I have to sort data by this column name.

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

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


See more on this question at Stackoverflow