C# ContainsKey Method (Key Exists in Dictionary)Use the ContainsKey method on the Dictionary to test for key existence.
dot net perls

ContainsKey. This is a Dictionary method. It computes the hash code for its argument. It then checks the internal structures in the Dictionary to see if that key exists.



Method notes. ContainsKey is extremely fast. It does no linear searching. It uses a hash code to estimate where the data is stored.


An example. You will find the ContainsKey method on a Dictionary. In Visual Studio, try typing the variable name and pressing period, and then scrolling to ContainsKey.


Part 1 The program populates the Dictionary with 2 key-value pairs. Each has a string key, and an int value.

Part 2 You can test ContainsKey in an if-statement. It will not throw exceptions on a key that is not found.


Part 3 If the key is not found, the inner body of the if-statement is not entered—so false is not printed here.

C# program that uses ContainsKey
using System; using System.Collections.Generic; class Program { static void Main() { // Part 1: create Dictionary with 2 key value pairs. var dictionary = new Dictionary<string, int>() { {"mac", 1000}, {"windows", 500} }; // Part 2: use ContainsKey method. if (dictionary.ContainsKey("mac") == true) { Console.WriteLine(dictionary["mac"]); } // Part 3: use ContainsKey on a key that does not exist. if (dictionary.ContainsKey("acorn")) { Console.WriteLine(false); } } }

Foreach Keys. Suppose we want to scan the keys of a Dictionary to match a certain condition (like strings that end in a number). We can use a foreach-loop over the Keys property.

Note This approach is much slower than ContainsKey, but if it has the correct result and is needed, it can be helpful.

Part 1 We create a Dictionary with 2 string keys and 2 bool values using an initializer.

Part 2 We use a foreach-loop over the Keys property, and call EndsWith on each key.


StartsWith, EndsWith

C# program that loops over Keys
using System; using System.Collections.Generic; class Program { static void Main() { // Part 1: create Dictionary. var ids = new Dictionary<string, bool>() { {"X1", true }, {"X2", true } }; // Part 2: use a foreach-loop on keys for more advanced scanning logic. foreach (var key in ids.Keys) { if (key.EndsWith("2")) { Console.WriteLine($"KEY ENDS WITH 2: {key}"); } } } }

Internals. The .NET Framework implements the ContainsKey method. Dictionary has a FindEntry() method which loops over the entries in the Dictionary that are pointed to by the buckets array.

And When it finds a matching hash code, it compares the key values and then returns the actual value.

Returns The ContainsKey method discards some of the values it finds and simply returns a Boolean.

Therefore Using TryGetValue can be used to perform these operations at one time, improving runtime speed.

Benchmark. A benchmark of ContainsKey compared to ContainsValue shows that ContainsKey is many times faster (the exact amount depends on the Dictionary size). This is important to know.

A summary. ContainsKey checks for a key's existence. Dictionary implements a lightning-fast lookup table. But it will throw exceptions if you try to access an entry when no key exists.

© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.