How to order Dates in Linq?

c#, entity-framework, linq

Solution

`events.OrderBy(x => x.DateTimeStart)`: Declare a query that sorts events by property DateTimeStart. The query is not performed yet.

`events.OrderBy(x => x.DateTimeStart).ToList();`: Process the previous query. Iterate through all events, checks their DateTimeStart, sort them and safe result as a List and then... discard the result! Because you didn't safe it. Compare it with something like that:

int a = 0;
a + 1;
b = a; // b is 0

`return events.AsQueryable();`: Here you are returning your original events instead of sorted.

You should write your code as follows:

return events.OrderBy(x => x.DateTimeStart).ToList().AsQueryable();

That version will create static list of sorted events. If now you change the events list, the result will not take into account your changes.

The second solution is:

return events.OrderBy(x => x.DateTimeStart).AsQueryable();

That version will do no work. It just declarates a manner to sort events and returns that manner as IQueryable. If you use returned value in future code it will always contain all sorted events even if you add new ones prior to use that.

Problem

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?

Original source