[英]Is there a usual style for using C#'s SortedDictionary<Key, Value> when you don't care about the value?
I'm using SortedDictionary<Key, Value>
to store a sorted list of Key
s, but don't care to store the Value
s. 我使用
SortedDictionary<Key, Value>
来存储Key
的排序列表 ,但不在乎存储Value
。 The Key
has one set of criteria for uniqueness and another for sorting (ie, the properties that GetHashValue()
and Equals(Object obj)
use are different than the ones used by CompareTo(Key key)
). Key
具有一组唯一性标准,另一个用于排序(例如, GetHashValue()
和Equals(Object obj)
使用的属性与CompareTo(Key key)
所使用的属性不同)。
I know that it is only storing a reference to the Value
, so the memory usage is small. 我知道它仅存储对
Value
的引用,因此内存使用量很小。 In my use case, I'll never need to access the Value
part of the KeyValuePair<Key, Value>
stored in the dictionary. 在我的用例中,我永远不需要访问存储在字典中的
KeyValuePair<Key, Value>
的Value
部分。
Is there some convention specifying what kind of object to use for Value
in these cases? 是否有约定指定在这些情况下将哪种对象用于
Value
? I'm currently using the same object for both Key
and Value
, that is, the type is Dictionary<Key, Key>
and the I'm using .Add(key, key)
to add objects. 我目前正在为
Key
和Value
使用相同的对象,即类型为Dictionary<Key, Key>
,而我正在使用.Add(key, key)
添加对象。
The same question applies to SortedList<Key, Value>
, but I need the insertion performance of SortedDictionary<Key, Value>
in this case. 相同的问题适用于
SortedList<Key, Value>
,但是在这种情况下,我需要SortedDictionary<Key, Value>
的插入性能。
If Value
is a reference type, storing it would waste from 4 to 8 bytes, depending on whether the process is 32-bit or 64-bit. 如果
Value
是引用类型,则存储它会浪费4到8个字节,具体取决于进程是32位还是64位。 If Value
is a value type, it may waste even more. 如果“
Value
是值类型,则可能浪费更多。
If you don't need it, you can set Value
to Byte
. 如果不需要,可以将
Value
设置为Byte
。 You can't go lower than 1 byte even with an empty struct. 即使使用空结构,也不能低于1个字节。 You can set to any value, probably 0 is a good choice.
您可以设置为任何值,大概为0是一个不错的选择。
Ideally, if all you need is a set, you should use a set. 理想情况下,如果您需要的只是一组,则应使用一组。
There's a SortedSet<T>
in .NET 4.0+ which uses a tree internally. .NET 4.0+中有一个
SortedSet<T>
,它在内部使用树。 In fact, SortedDictionary<TKey, TValue>
uses SortedSet<KeyValuePair<TKey, TValue>>
internally. 实际上,
SortedDictionary<TKey, TValue>
使用SortedSet<KeyValuePair<TKey, TValue>>
。
The set counterpart of SortedList<TKey, TValue>
is a List<T>
, I guess. 我猜想
SortedList<TKey, TValue>
对应SortedList<TKey, TValue>
是List<T>
。 You'll just need to use binary search and insert values into sorted positions. 您只需要使用二进制搜索并将值插入已排序的位置即可。 Implementing
ISet<T>
should be simple. 实现
ISet<T>
应该很简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.