[英]DateTime as key in a SortedDictionary<K, V>
Can I safely use DateTime
as a key in a SortedDictionary<K, V>
without implementing my own IComparer
? 我可以安全地使用
DateTime
作为SortedDictionary<K, V>
而不实现我自己的IComparer
吗?
I've tried it and sort order is maintained and importantly for my purpose the .ContainsKey<T>
method works as expected. 我已经尝试了它并且维护了排序顺序,重要的是我的目的
.ContainsKey<T>
方法按预期工作。 But I just want to double check before committing myself down this road. 但我只想在将自己投入这条道路之前进行双重检查。
I works well because DateTime
implements IComparable<DateTime>
. 我工作得很好,因为
DateTime
实现了IComparable<DateTime>
。 So you can rely in the Comparer(T).Default . 所以你可以依赖Comparer(T).Default 。
Internally, the DateTime
uses ticks to compare 2 dates. 在内部,
DateTime
使用刻度来比较2个日期。
you will not need a new IComparer. 你不需要新的IComparer。 your default IComparer will use the GetHashCode() from your value object and compare/sort with that.
您的默认IComparer将使用您的值对象中的GetHashCode()并与之进行比较/排序。 Since the DateTime type implements the GetHashCode() correctly, the default IComparer will sort as you want it to (like you have discovered).
由于DateTime类型正确实现了GetHashCode(),因此默认IComparer将按您的意愿排序(就像您发现的那样)。
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.
这有点令人兴奋。
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. 此外,确保所有值都基于相同的时区 - 我个人使用UTC / GMT进行存储和计算,并在显示时仅调整到当地时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.