简体   繁体   English

在C#字典中查找元组键的问题

[英]Problems with finding tuple key in c# dictionary

Dictionary<Tuple<int, int>, link_data> dic_links

I have the above code. 我有上面的代码。 I use tuple as the dictionary key. 我使用元组作为字典键。 I want to find value using only one of the two values ​​in tuple. 我只想使用元组中两个值之一来查找值。

Is there any way to find it using only index instead of searching the entire dictionary in foreach? 有什么方法可以只使用索引而不是在foreach中搜索整个词典来找到它吗?

cout << dic_links[new Tuple<int, int>(57,**).data;

No, it is not possible to use only partial key to search in a dictionary with O(1) performance. 不可以,不能仅使用部分键在具有O(1)性能的字典中进行搜索。

Your options are either search through all key or have separate dictionary to map each part of the key to object (make sure to keep them in sync). 您可以选择搜索所有键,也可以使用单独的词典将键的每个部分映射到对象(请确保它们保持同步)。

If you only need to search by full key or one component and O(log n) is reasonable you can use sorted list instead (you will not be able to search by second component with single array). 如果只需要按全键或一个组成部分进行搜索,并且O(log n)是合理的,则可以使用排序列表(您将无法使用单个数组按第二个组成部分进行搜索)。


For more ideas you can search for "range queries on dictionaries" where one would like to find "all items with key 10 to 100" which is the same problem. 有关更多的想法,您可以搜索“字典范围查询”,在其中您希望找到“所有键为10到100的项”,这是同样的问题。

No. The Dictionary is designed for efficient search using strict equality of the key. 不可以。该Dictionary旨在使用严格的键相等性进行有效搜索。 If you don't know exactly the key, then you must enumerate all elements one-by-one. 如果您不确切知道密钥,则必须一个一枚举所有元素。

In your case you'll probably have duplicate values on each individual property of the tuple, so you'll not be able to use a simple Dictionary<int, link_data> for indexing by property. 在您的情况下,您可能在元组的每个单独属性上都有重复的值,因此您将无法使用简单的Dictionary<int, link_data>来按属性进行索引。 You could use either a Lookup<int, link_data> if your data are static, or a Dictionary<int, List<link_data>> if you need to add/remove elements after the creation of the index. 如果您的数据是静态的,则可以使用Lookup<int, link_data> Dictionary<int, List<link_data>>如果需要在创建索引之后添加/删除元素,则可以使用Dictionary<int, List<link_data>>

您可以将字典转换为嵌套字典。

Dictionary<int, Dictionary<int, link_data>>dic_links;

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

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