ContainsKey
This is a C# Dictionary
method. It computes the hash code for its argument, and then checks the internal structures in the Dictionary
to see if that key exists.
ContainsKey
is extremely fast. It does no linear searching—instead, it uses a hash code to estimate where the data is stored.
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
.
Dictionary
with 2 key-value pairs. Each has a string
key, and an int
value.ContainsKey
in an if
-statement. It will not throw exceptions on a key that is not found.if
-statement is not entered—so false is not printed here.using System; using System.Collections.Generic; // 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); }1000
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.
ContainsKey
, but if it has the correct result and is needed, it can be helpful.Dictionary
with 2 string
keys and 2 bool
values using an initializer.foreach
-loop over the Keys
property, and call EndsWith
on each key.using System; using System.Collections.Generic; // 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}"); } }KEY ENDS WITH 2: X2
The .NET runtime 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.
ContainsKey
method discards some of the values it finds and simply returns a Boolean
.TryGetValue
can be used to perform these operations at one time, improving runtime speed.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.
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.