'How can I sort on nullable DateTime fields? [duplicate]
I have the following line of C# code:
dueEvents.Sort((e1, e2) => e1.EventDateGmt.CompareTo(e2.EventDateGmt));
dueEvents
is a List. The EventDateGmt
fields are each a DateTime. This compiles.
I change it to this:
dueEvents.Sort((e1, e2) => e1.EventDateLocal.CompareTo(e2.EventDateLocal));
EventDateLocal is a DateTime?
. This causes the following compiler error:
CS7036: There is no argument given that corresponds to the required comparison type...
How can I sort on EventDateLocal
?
Solution 1:[1]
Since DateTime?
values can be null
we can't compare them directly. We
should decide if null
value is less (nulls first) or greater (nulls last)
than any other value. For instance:
// Nulls First
dueEvents.Sort((left, right) => {
// We have to deal with nulls...
if (!left.HasValue)
return !right.HasValue ? 0 : -1;
else if (!right.HasValue)
return 1;
// Both left and right are not null, that's why we can do business as usual
// and compare Values which are not null
return left.Value.CompareTo(right.Value);
});
Or
// Nulls Last
dueEvents.Sort((left, right) => {
if (!left.HasValue)
return !right.HasValue ? 0 : 1;
else if (!right.HasValue)
return -1;
return left.Value.CompareTo(right.Value);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dmitry Bychenko |