0

I have a list of dates as strings in the format 'dd/mm/yyyy hh:mm:ss tt' I'm trying to order them by closest to farthest like so:

09/12/2018 12:00:00 PM
10/12/2018 12:00:00 PM
11/12/2018 12:00:00 PM

My code seems to be ordering them from the 11th to the 09th which I don't want but can't seem to get right.

DateTime now = DateTime.Now;
var ordered = herds.HerdList.OrderBy(n => (now - DateTime.Parse(n.Date_Visit)).Duration());

The above code gives me:

11/12/2018 12:00:00 PM
10/12/2018 12:00:00 PM
09/12/2018 12:00:00 PM

How can I order it the other way around?

Thanks

SmiffyKmc
  • 801
  • 1
  • 16
  • 34
  • _I have a list of dates as strings"_ Why the `Date_Visit`-dates are strings at all? – Tim Schmelter Mar 16 '18 at 10:09
  • Just coming from the Web Service and sending to the Web Service. I parse it to a Date to work with in Time. – SmiffyKmc Mar 16 '18 at 10:10
  • So basically get the date and time of when the object was created, turn to string and send to web service to be saved in the cloud. – SmiffyKmc Mar 16 '18 at 10:11
  • Order by descending? – Kevin Avignon Mar 16 '18 at 10:11
  • Omg, I'm this stupid ><. No coffee this morning I'll give that a shot there. – SmiffyKmc Mar 16 '18 at 10:12
  • First step: Make your property `Date_Visit` of type `DateTime` and convert the incoming data accordingly. If this works as expected and you still have issues in ordering come back. – Oliver Mar 16 '18 at 10:12
  • Order by descending worked...can't believe I didn't think of that. Thanks, @KevinAvignon. Thanks for your input Oliver – SmiffyKmc Mar 16 '18 at 10:14
  • This would make a great of any "Order by descending" from the linQ tag. As "order it the other way around" is quite a uncommon way to call it. – Drag and Drop Mar 16 '18 at 10:29
  • Possible duplicate of [OrderBy descending in Lambda expression?](https://stackoverflow.com/questions/1635497/orderby-descending-in-lambda-expression) – Drag and Drop Mar 16 '18 at 10:30

3 Answers3

1

How can I order it the other way around?

Use OrderByDescending instead of OrderBy

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • You were first and saw you deleted the answer. Will mark this. Sorry for wasting your time, won't ask questions without coffee next time xD – SmiffyKmc Mar 16 '18 at 10:16
1

You can flip the order of any Orderby(x => whatever) by simply using OrderByDescending(x => whatever).

Flater
  • 12,908
  • 4
  • 39
  • 62
1

var ordered = herds.HerdList.OrderBy(n => DateTime.Parse(n.Date_Visit));