events.OrderBy(x => x.DateTimeStart) : declare a request that sorts events by the DateTimeStart property. The request has not yet been completed.
events.OrderBy(x => x.DateTimeStart).ToList(); : process the previous request. Iterate over all events, check their DateTimeStart, sort them and secure the result in a list, and then ... undo the result! Because you are not safe. Compare this to something like this:
int a = 0; a + 1; b = a;
return events.AsQueryable(); : here you return the source events instead of sorting.
You should write your code as follows:
return events.OrderBy(x => x.DateTimeStart).ToList().AsQueryable();
This version will create a static list of sorted events. If you now change the list of events, the result will not take into account your changes.
The second solution:
return events.OrderBy(x => x.DateTimeStart).AsQueryable();
This version will not work. It simply declares a way to sort events and returns it as IQueryable. If you use the return value in future code, it will always contain all sorted events, even if you add new ones before use.
source share