DateTime作为SortedDictionary中的键< K,V> [英] DateTime as key in a SortedDictionary<K, V>

查看:129
本文介绍了DateTime作为SortedDictionary中的键< K,V>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以安全地使用 DateTime 作为 SortedDictionary code> IComparer ?

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

我已经尝试了它,排序顺序保持,重要的是为了我的目的 .ContainsKey< T> 方法按预期工作。但是我只是想在这条路之前仔细检查。

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.

这篇关于DateTime作为SortedDictionary中的键&lt; K,V&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆