- Home /
How to add dictionary keys with defined values to a list
I am trying to add dictionary keys with player-defined values into a list, for example if playertypes 1 into input field, the programm will add into the list all keys with value 1, but i can't figure out how
Answer by Orokon · Jan 13, 2018 at 05:38 PM
Get the input in the code and use its .text
value. With that value you can now get elements out of a dictionary like:
Dictionary<string, GameObject> dictionary = new Dictionary<string, GameObject>();
InputField input = FindObjectOfType<InputField>();
input.text = "foo";
GameObject elementFromDictionary = dictionary[input.text];
If you want to populate a dictionary by player defined key and value then get the values and add it like this:
Dictionary<string, GameObject> dictionary = new Dictionary<string, GameObject>();
string key = "foo"; // Get this from whatever the player enters
GameObject foo = new GameObject(); // This is the userdefined value
dictionary.Add(key, foo); // pass the key and the stuff you want to have in the dictionary
I'm sorry but this doesn't help me. I already have values and keys stored in Dictionary. What I want to know is how to put it's keys that have the user defined value into a list
Okay that clears things up:
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("foo", 10);
dictionary.Add("bar", 20);
dictionary.Add("baz", 10);
List<string> listWith$$anonymous$$eys = new List<string>();
foreach ($$anonymous$$eyValuePair<string, int> dictionaryItem in dictionary) {
if (dictionaryItem.Value == 10) {
listWith$$anonymous$$eys.Add(dictionaryItem.$$anonymous$$ey);
}
}
In this case the value 10 is what the user typed into the input.