Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET dictionary with two keys and one value

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?

like image 622
Nuts Avatar asked Sep 24 '15 12:09

Nuts


People also ask

Can a dictionary have two keys with the same value?

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.

Can a dictionary have two keys in C#?

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.

How many values can a dictionary hold C#?

I think the dictionary only has one key value.

Can a dictionary key be a string in C#?

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.


1 Answers

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.)

like image 127
Ian Ringrose Avatar answered Oct 13 '22 22:10

Ian Ringrose