How to order dates in Link?

I use C # and LINQ, I have a date in type Date

I am currently using this script to sort the list by start date, from earlier to last.

In the following code, my events are not sorted:

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

What could be wrong here?

+6
source share
3 answers

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; // b is 0 

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.

+4
source

events.OrderBy(x => x.DateTimeStart).ToList() creates a new list and you do not return it.

You probably want something like

 return events.OrderBy(x => x.DateTimeStart).ToList(); 
+12
source

save your ordered events in a variable and return this variable asQueryable ();

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

or if you do not need this variable, immediately return the ordered events.

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

All Articles