I am using C# and LINQ, I have some Date in type Date
At the moment I am using this script to order a list by date of start, from the earlier to the latest.
With the following code my events are not sorted:
events.OrderBy(x => x.DateTimeStart).ToList();
return events.AsQueryable();
What could be wrong here?
LINQ includes five sorting operators: OrderBy, OrderByDescending, ThenBy, ThenByDescending and Reverse. LINQ query syntax does not support OrderByDescending, ThenBy, ThenByDescending and Reverse. It only supports 'Order By' clause with 'ascending' and 'descending' sorting direction.
If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.
In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order. We don't need to add any ascending condition in the query statement.
When arranging them in ascending order they are arranged from A to Z – or beginning to end. When it comes to dates, ascending order would mean that the oldest ones come first and the most recent ones last.
events.OrderBy(x => x.DateTimeStart).ToList()
creates a new list, and you don't return it.
You probably want something like
return events.OrderBy(x => x.DateTimeStart).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With