Is there a dictionary available in .NET
that could hold 2 keys and one value. Like
Dictionary(Of TKey, Of TKey, TValue)
I have a need to store two keys and at certain times look an item by the key 1 and at other times by the key 2.
My current solution is to maintain two dictionaries
Dictionary<string, long> Dict1 = new Dictionary<string, long>(); Dictionary<long, long> Dict2 = new Dictionary<long, long>();
and when need to add item I will add it to both dictionaries.
Dict1.Add("abc", 111); Dict2.Add(345, 111);
and then I will look up an item from either one of those dictionaries depending by which one of the keys I need to look by.
Same I will do when deleting or updating an item.
I have thought about the composite key but I don't know how to set it up and I don't want to lose any speed of searching the item.
Is there some solution available in .NET
to have dictionary that can hold multiple keys?
Answer. No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored.
It's a dictionary of dictionaries, so you have 2 keys to access each object, the key for the main dictionary to get you the required sub dictionary, and then the second key for the sub dictionary to get you the required item.
I think the dictionary only has one key value.
Add elements to a C# Dictionary Both types are generic so it can be any . NET data type. The following Dictionary class is a generic class and can store any data type. This class is defined in the code snippet creates a dictionary where both keys and values are string types.
As you wish your value to be “findable” from either key, I would just use two dictionaries like you are doing now. However I would wrap this up in a class, with methods names like FindByXXX
and FindByYYY
.
The much harder question is how do you do a delete, as you need to know both keys at the time of the delete. Maybe your value stores both keys so you can pass the value into your delete method. Maybe you never need to remove items from the dictionaries. Or the code that needs to remove items knows both keys.
Hence there is no standard dictionary to do this, as the requirements are different between each user.
(Note you don’t want a dictionary with a composite key, as that would require you to know both keys whenever you wished to look up an item.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With