I have a dictionary where I am storing a key and 2 values in a tuple like so:
variableDictionary = new Dictionary<string, Tuple<string, string>>();
So my dictionary is: key, <value1, value2>
I want to check if a value1 is already stored in the dictionary. If my dictionary was string for the key and string for the value I could just use ContainsValue.
bool alreadyStored = variableDictionary.ContainsValue(value1);
I'm not sure how to find whether my value1 is in the dictionary in the value1 part of the tuple regardless of what the value2 is. I could create a new tuple and check whether it contains this tuple but I'm not sure how to make it effectively ignore the second value.
A tuple is defined and is displayed on the console. A dictionary is defined and is displayed on the console. The tuple is converted to a list, and the dictionary is added to it using the 'append' method. Then, this resultant data is converted to a tuple.
A tuple containing a list cannot be used as a key in a dictionary. Answer: True. A list is mutable. Therefore, a tuple containing a list cannot be used as a key in a dictionary.
Answer. Yes, a tuple is a hashable value and can be used as a dictionary key. A tuple would be useful as a key when storing values associated with a grid or some other coordinate type system.
The Tuple method is similar to the above snippets, and while it is faster than the Dictionary<int, KeyValuePair<string, string>> , it is still nowhere near as fast as indexing directly into the collection to the desired value based on a hashed key, as is done in the MultiKeyDictionary class.
ContainsValue
performs simple linear search, so you can do the same with LINQ pretty easily:
bool alreadyStored = variableDictionary.Any(x => x.Value.Item1 == value1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With