Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
352 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...