DateTime作为SortedDictionary 中的键(DateTime as key in a SortedDictionary)

编程入门 行业动态 更新时间:2024-10-28 07:18:44
DateTime作为SortedDictionary 中的键(DateTime as key in a SortedDictionary)

我可以安全地使用DateTime作为SortedDictionary<K, V>中的一个键,而无需实现我自己的IComparer ?

我试过了,排序顺序保持不变,对我的目的来说很重要.ContainsKey<T>方法按预期工作。 但我只是想在这条道路上投入自己之前仔细检查。

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.

最满意答案

你将不需要一个新的IComparer。 您的默认IComparer将使用您的值对象中的GetHashCode()并与其进行比较/排序。 由于DateTime类型正确地实现了GetHashCode(),因此默认的IComparer将按照您的需要进行排序(就像您发现的那样)。

创建新的比较器更适合您自己编写的复杂集合。 我写了一次复杂的比较器。 这有点令人兴奋。

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.

更多推荐

本文发布于:2023-08-02 03:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1369866.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:DateTime   SortedDictionary   key

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!