I'm looking for a way to get multiple keys with a single value. Yes, I've already used the search function, but most answers are for the opposite direction (multiple values per key), but I want the opposite.
The reasoning behind this is that I want keep multiple Item-IDs (it's for a Bot) per "main" ID, and throwing those multiple IDs into a value of the one is too slow to modify (looking for one value => looping trough all main IDs & getting each value, then checking if that ID exists).
Example
Key 1 => Value
Key 2 => Value
Key 3 => Value
Key 4 => Value
Key 5 => Value 2
Looking for Value should return: Key 1-4, not 5
So I'm looking for a way to do that easier - like I said above.
Anyone knows if that's possible and how to do it? Thanks in advance.
Edit: Looking at your edit, it really looks like you have designed this
Dictionary
backwards... your keys should be for matching values, not your values for matching keys.You could do something like create a dictionary that maps outer-keys to inner-keys, then use the inner-key to index a second dictionary.
Example:
You would access it as:
value = outer[inner[key]]
.1) Servy is absolutely correct. If you're doing a search on anything but a key ... and if you're trying to retrieve anything but the corresponding value ... then something is definitely wrong. All things being equal, you probably DON'T want a dictionary.
2) Based on what you're saying, perhaps a better collection type might be a List. Specifically, a list of name/value pairs.
EXAMPLE:
3) Note that .Net has a specialized "NameValueCollection" class that might be IDEAL for you:
Do the dictionary the other way around and make the value a list of items.
if for example
Value
is a string andKey 1-4
are ints your dictionary could look something like:retrieving
Value
bytheDictionary["Value"]
would then return a list of ints containing 1, 2, 3 and 4.Edit - Added example:
You may be overthinking your problem. Keys need to be unique in order to be useful for lookup operations. Values do not need to be unique. Multiple keys can point to the same value without causing problems.
Assuming you have your initial dictionary (mapping your keys to values) already you can use some Linq to convert it into a reverse dictionary without having to create that reverse dictionary by hand.
Select the distinct
originalValues
from your original dictionary and use those as yournewKeys
. YournewValues
are the set of youroriginalKeys
that mapped to eachoriginalValue
/newKey
.Example: https://dotnetfiddle.net/dhwUSC
Given an initial dictionary of
the above function returns