C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Sometimes you cannot access a Dictionary only by looking up keys and need to search for a specific value. This method on the Dictionary type provides this functionality.
Example. The ContainsValue method receives one parameter of the type specified as the value type in the Dictionary. When you declare the Dictionary, you specify two type parameters. The second, TValue parameter is the type used in ContainsValue.
Here: This example shows how the ContainsValue searches all entries in the Dictionary for a match and returns a bool.
C# program that uses ContainsValue using System; using System.Collections.Generic; class Program { static void Main() { // // This dictionary contains stock symbols and market caps. // ... Values are in billions of USD. // var caps = new Dictionary<string, decimal>(); caps.Add("msft", 215); caps.Add("xon", 348); caps.Add("goog", 132); caps.Add("wmt", 188); // // See if there are stocks with these capitalizations. // bool flag1 = caps.ContainsValue(348); bool flag2 = caps.ContainsValue(1000); bool flag3 = caps.ContainsValue(188); // // The first call matches "xon"; // The second call returns false; // The third call matches "wmt". // Console.WriteLine(flag1); Console.WriteLine(flag2); Console.WriteLine(flag3); } } Output True False True
In this example, a new Dictionary containing keys of type string and values of type decimal is instantiated. It is populated with four stock symbols and their market valuations in billions of USD.
Note: The companies are Microsoft, Exxon, Google and Wal-Mart. This information is not important. I am sharing it anyways.
The three bool variables flag1, flag2 and flag3 are assigned the results of ContainsValue on various parameters. In Code Complete using the variable name of "flag" is discouraged because it does not describe the code's intent.
Also: In Refactoring, Martin Fowler suggests eliminating temporary variables and using the method calls themselves as the expressions.
Discussion. ContainsKey will compute a hash code of the key and use that to locate the value for that key in near-constant time. ContainsValue will loop through all the entries in the Dictionary. It checks the value of each element.
And: For this reason, using ContainsValue is far slower in most cases than ContainsKey.
Summary. We saw how to use the ContainsValue method on the Dictionary generic class in the C# programming language targeting the .NET Framework. We saw an example of how this method can be used to search the values in a Dictionary.