Reputation: 562
I am using a LINQ query to get the data order by descending date. but when the year is changed then descending order of date is not in the proper way
Here is my code
In this code, LastLogin is a 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)
.ToList();
Upvotes: 3
Views: 1843
Reputation: 1500805
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)
.Distinct()
.OrderByDescending(x => x)
.Select(x => x.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture))
.ToList();
Upvotes: 6
Reputation: 13146
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) })
.ToList();
Upvotes: 9