Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dictionary.ContainsValue with tuple as the value

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.

like image 355
Dan Smith Avatar asked Aug 05 '14 00:08

Dan Smith


People also ask

Can we have tuple in dictionary python?

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.

Can a dictionary have 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.

Can a tuple be a dictionary key C#?

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.

Which is faster tuple or dictionary in C#?

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.


1 Answers

ContainsValue performs simple linear search, so you can do the same with LINQ pretty easily:

bool alreadyStored = variableDictionary.Any(x => x.Value.Item1 == value1);
like image 96
MarcinJuraszek Avatar answered Sep 29 '22 18:09

MarcinJuraszek