Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order Dates in Linq?

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?

like image 608
GibboK Avatar asked Feb 22 '13 08:02

GibboK


People also ask

How to sort LINQ?

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.

How do I get data in descending order in LINQ?

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.

How do I use ascending order in LINQ?

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.

What is ascending order for dates?

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.


1 Answers

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(); 
like image 181
sloth Avatar answered Sep 29 '22 18:09

sloth