DateTime as key in SortedDictionary <K, V>

Can I safely use DateTime as a key in a SortedDictionary<K, V> without implementing my own IComparer ?

I tried and the sort order is supported, and important for my purpose .ContainsKey<T> works as expected. But I just want to double check before setting off on this road.

+4
source share
3 answers

You will not need a new IComparer. your default IComparer will use GetHashCode () from your value object and compare / sort with it. Since the DateTime type correctly implements GetHashCode (), by default, IComparer will sort as you wish (for example, you find).

Creating a new mapping is more for complex collections that you may have written yourself. I wrote a complex comparator once. it is a bit tiring.

+7
source

I work well because DateTime implements IComparable<DateTime> . So you can rely on Comparer (T) .Default .

Inside, DateTime uses ticks to compare two dates.

+9
source

I do not foresee any problems; behind the scenes, the value is a long checkmark value.

Also, make sure that all values ​​are based in the same time zone - I personally use UTC / GMT to store and calculate and only adapt to the local time when displaying.

+4
source

All Articles