Determine if a key exists in a Dictionary in C#
This post will discuss how to determine whether a key exists in a Dictionary in C#.
1. Using ContainsKey() method
We can use the ContainsKey() method to determine whether the Dictionary contains an element with the specified key. The following example demonstrates this.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, string> dict = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" }, { "key3", "value3" } }; string key = "key2"; bool keyExists = dict.ContainsKey(key); if (keyExists) { Console.WriteLine("{0} exists in map", key); } else { Console.WriteLine("{0} does not exist in map", key); } } } /* Output: key2 exists in map */ |
2. Using Dictionary.TryGetValue() method
TryGetValue() method returns true if the Dictionary contains an element with the specified key; otherwise, false. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, string> dict = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" }, { "key3", "value3" } }; string key = "key2"; string value; bool keyExists = dict.TryGetValue(key, out value); if (keyExists) { Console.WriteLine("{0} exists in map", key); } else { Console.WriteLine("{0} does not exist in map", key); } } } /* Output: key2 exists in map */ |
That’s all about checking if a key exists in a Dictionary in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)