简体   繁体   English

从SortedDictionary获取等于项的键?

[英]Get a key equal to an item from SortedDictionary?

Is there any way to retrieve a key from a SortedDictionary that is equal to a given object? 有什么方法可以从SortedDictionary中检索与给定对象相等的键? To illustrate, lets say I create a dictionary that has a fairly memory-heavy, immutable key type: 举例说明,假设我创建了一个字典,该字典具有相当大的内存且不可变的键类型:

var dictionary = SortedDictionary<MyHugeType, int>();
var myEnormousKey = new MyHugeType();

dictionary[myEnormousKey] = 123;

Then later on, I do something like this: 然后,稍后我将执行以下操作:

// This is a new instance, but it's identical to the previous key
var myIdenticalKey = new MyHugeType();

if(dictionary.ContainsKey(myIdenticalKey)) {
    myIdenticalKey = dictionary.GetKeyEqualTo(myIdenticalKey);
}

// Use myIdenticalKey reference...

Obviously, SortedDictionary does not have a "GetKeyEqualTo" method. 显然,SortedDictionary没有“ GetKeyEqualTo”方法。 But is there some way I could achieve a similar effect? 但是有什么方法可以达到类似的效果吗? This would basically have the effect of intern-ing the heavy key objects so that identical instances could be discarded. 基本上,这将具有重载关键对象的作用,因此可以丢弃相同的实例。 I know I can do this using the SortedList class by retrieving the key's index and subsequently its matching object instance, but SortedDictionary's consistent insertion performance would be better for my uses. 我知道我可以使用SortedList类通过检索键的索引及其随后的匹配对象实例来做到这一点,但是SortedDictionary的一致插入性能对于我的使用会更好。

Short of iterating through all the dictionary's keys to search for a match, or writing my own BST class, is there any way to achieve this end with .NET's built in collections? 除了遍历字典中的所有键以查找匹配项或编写我自己的BST类之外,.NET的内置集合是否有办法实现这一目标?

You could change your value object from int to a struct or class containing both the value and the original key. 您可以将value对象从int更改为同时包含value和原始键的struct或class。 Then to access the original key you can do: 然后,可以访问原始密钥:

dictionary[myIdenticalKey].OriginalKey

and for the value something like: 和价值的东西像:

dictionary[myIdenticalKey].Value

You could implement the IEquatable interface in your key class. 您可以在键类中实现IEquatable接口。 There you specify when two objects of the class are equal to each other. 在此指定类的两个对象何时相等。 After that you simply test the existence of an entry using ContainsKey and when that returns true you can obtain it using the [] operator. 之后,您只需使用ContainsKey测试条目是否存在,当返回true时,就可以使用[]运算符获取它。

You could also provide a IComparer implementation to achieve the same result. 您还可以提供IComparer实现以实现相同的结果。

If you override Equals() and GetHashCode() in MyHugeType with code that determines if two instances are the same, then you won't get duplicate keys in the dictionary. 如果使用确定两个实例是否相同的代码覆盖MyHugeType Equals()GetHashCode() ,则在字典中不会得到重复的键。 Is this what you mean? 你是这个意思吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM