Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

c# - .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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...