C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: The second type parameter, TValue, is the type used when calling ContainsValue.
New: A new Dictionary containing keys and values of string type is created. It is populated with animal names and their default colors.
Variables: The variables flag1, flag2 and flag3 are assigned the results of ContainsValue.
Returns: This example shows how ContainsValue() searches all entries in the Dictionary for a match and returns a bool.
BoolC# program that uses ContainsValue
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Store animal colors.
var animalColors = new Dictionary<string, string>();
animalColors.Add("bird", "blue");
animalColors.Add("worm", "pink");
animalColors.Add("cat", "black");
animalColors.Add("dog", "brown");
// See if colors exists.
bool flag1 = animalColors.ContainsValue("black");
bool flag2 = animalColors.ContainsValue("clear");
bool flag3 = animalColors.ContainsValue("blue");
// Write results.
Console.WriteLine(flag1);
Console.WriteLine(flag2);
Console.WriteLine(flag3);
}
}
Output
True
False
True
Version 1: This version of the code uses ContainsValue. It repeatedly calls ContainsValue with a key that exists in the Dictionary.
Version 2: Here we use ContainsKey instead. The key exists in the Dictionary, and we access it many times.
Result: Checking for the existence of a key (with ContainsKey) is much faster than checking for a value (with ContainsValue).
C# program that benchmarks ContainsKey, ContainsValue
using System;
using System.Collections.Generic;
using System.Diagnostics;
class Program
{
const int _max = 10000;
static void Main()
{
// Create a lookup table.
var lookup = new Dictionary<string, string>();
for (int i = 0; i < 1000; i++)
{
lookup[i.ToString() + "a"] = i.ToString() + "b";
}
// Version 1: use ContainsValue.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
if (!lookup.ContainsValue("999b"))
{
return;
}
}
s1.Stop();
// Version 2: use ContainsKey.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
if (!lookup.ContainsKey("999a"))
{
return;
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
Console.Read();
}
}
Output
13388.79 ns ContainsValue
37.49 ns ContainsKey
And: ContainsValue checks the value of each element. For this reason, using ContainsValue is far slower in most cases than ContainsKey.