Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: sort list of objects by DateTime property that is nullable

Tags:

c#

linq

I have a List of objects: List<FakeObject> list = ...

Each object has a DateTime property, let's call it "Date"

I want to sort this list by this date property in descending order. However, when I try

list.Sort(new Comparison<FakeObject>((x, y) => DateTime.Compare(x.Date, y.Date)))

it complains because the Date property can be nullable.

How do I sort this list, where it treats nullable dates as MAX DATE, so it appears in the top? The quick easy alternative for me is to NOT make the Date field nullable, but let's suppose that's not an option right now.

In short: How do I sort a list of objects by DateTime, if the DateTime can be null?

like image 494
Henley Avatar asked Nov 01 '13 18:11

Henley


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C language?

C is an imperative procedural language supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support.

What is C full form?

Full form of C is “COMPILE”. One thing which was missing in C language was further added to C++ that is 'the concept of CLASSES'.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


2 Answers

One possible approach might be:

list.Sort(new Comparison<FakeObject>((x, y) => 
    -DateTime.Compare(x.Date ?? DateTime.MaxValue,
        y.Date ?? DateTime.MaxValue)));

UPDATE: modified to use MaxDate after the OP edited the question for clarification.

Note that you could do this either way (MinDate or MaxDate). The bottom line is this, if it's null then give it some static value that accomplishes what you want.

like image 191
Mike Perrenoud Avatar answered Oct 01 '22 05:10

Mike Perrenoud


If you want to convert all null dates to the max date value then just do that in your function. You can use the null coalesce operator for a more succinct syntax for this:

list.Sort((x, y) => 
    DateTime.Compare(x.Date ?? DateTime.MaxValue, y.Date ?? DateTime.MaxValue))
like image 43
Servy Avatar answered Oct 01 '22 06:10

Servy