Reputation: 31
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?
cout << dic_links[new Tuple<int, int>(57,**).data;
Upvotes: 2
Views: 2182
Reputation: 36
You can convert the dictionary to a nested dictionary.
Dictionary<int, Dictionary<int, link_data>>dic_links;
Upvotes: 0
Reputation: 43409
No. The Dictionary
is designed for efficient search using strict equality of the key. 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. 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.
Upvotes: 1
Reputation: 100527
No, it is not possible to use only partial key to search in a dictionary with O(1) performance.
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).
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.
Upvotes: 1