DateTime as key in a SortedDictionary<K, V>

旧时模样 提交于 2020-01-14 09:39:57

问题


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

I've tried it and sort order is maintained and importantly for my purpose the .ContainsKey<T> method works as expected. But I just want to double check before committing myself down this road.


回答1:


you will not need a new IComparer. your default IComparer will use the GetHashCode() from your value object and compare/sort with that. Since the DateTime type implements the GetHashCode() correctly, the default IComparer will sort as you want it to (like you have discovered).

creating new comparer's is more for complex collections that you may have written yourself. i wrote a complex comparer once. it's a bit mind blowing.




回答2:


I works well because DateTime implements IComparable<DateTime>. So you can rely in the Comparer(T).Default.

Internally, the DateTime uses ticks to compare 2 dates.




回答3:


I don't foresee any problems; behind the scenes the value is a long tick value.

Also, ensure that all of the values are based in the same time zone - personally I use UTC/GMT for storing and calculating and only adjust to local time when displaying.



来源:https://stackoverflow.com/questions/453124/datetime-as-key-in-a-sorteddictionaryk-v

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!