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?
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 ...
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.
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'.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With