简体   繁体   English

DateTime作为SortedDictionary <K,V>中的键

[英]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.

相关问题 为什么SortedDictionary <K,V> .GetEnumerator O(log n)但SortedSet <T> .GetEnumerator O(1)? - Why is SortedDictionary<K, V>.GetEnumerator O(log n) but SortedSet<T>.GetEnumerator O(1)? 带复合键的SortedDictionary:按1个属性建立索引,然后按另一个属性进行排序 - SortedDictionary with composite key: indexed by 1 property and sorted by another 从SortedDictionary获取等于项的键? - Get a key equal to an item from SortedDictionary? 快速找到SortedDictionary中第一个未使用的密钥? - Fast way to find the first unused key in a SortedDictionary? 如何使用对象的身份作为字典的键<K,V> - How to use an object's identity as key for Dictionary<K,V> 如何从SortedDictionary获取以前的密钥? - How do I get previous key from SortedDictionary? 如何从 SortedDictionary 中获取离我的键最近的项目? - How to get the closest item to my key from a SortedDictionary? SortedDictionary将一个SortedDictionary添加到另一个 - SortedDictionary add one SortedDictionary into another 是否有使用C#的SortedDictionary的常用样式 <Key, Value> 当您不在乎价值时? - Is there a usual style for using C#'s SortedDictionary<Key, Value> when you don't care about the value? 使用KeyValuePair <K,V>的AutoMapper无法映射 - No mapping with AutoMapper with KeyValuePair<K, V>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM