leora
leora

Reputation: 196459

In C#, what is the best way to sort by DateTime? and have the empty ones at the end?

I have an array of DateTime? objects and I want to sort them to render them on a webpage. The issue is that the ones with no value seem to show up at the top of the list and I want them to show up at the bottom.

What is the best way to sort an array of DateTime? that will have the items with no value set show up at the bottom.

So instead of this:

  1. [No Value]
  2. Jan 1, 2013
  3. Jan 15, 2013

I want this:

  1. Jan 1, 2013
  2. Jan 15, 2013
  3. [No Value]

Upvotes: 1

Views: 138

Answers (2)

Anthony Pegram
Anthony Pegram

Reputation: 126804

You should be able to utilize the null coalescing operator. For example:

var orderedDates = nullableDates.OrderBy(date => date ?? DateTime.MaxValue);

This will subsitute the maximum value for any missing (null) dates, pushing those to the end of the sorted sequence. If this date is presumably part of an object, you can of course use this to order a sequence by a date property of the object.

var orderedFoos = foos.OrderBy(foo => foo.SomeDate ?? DateTime.MaxValue);

Upvotes: 10

Fede
Fede

Reputation: 44038

var ordered = dates.OrderBy(x => x ?? DateTime.MaxValue);

Upvotes: 0

Related Questions