Remove a key from a Dictionary in C#
This post will discuss how to remove a key from a Dictionary in C#.
1. Using Dictionary<TKey,TValue>.Remove()
Method
The standard solution to remove a value with the specified key from a dictionary is using the Dictionary<TKey,TValue>.Remove()
method. The following example uses the Remove()
method to remove a key-value pair from a dictionary.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3}, {"D", 4} }; var keyToRemove = "D"; dict.Remove(keyToRemove); Console.WriteLine(String.Join(", ", dict)); // [A, 1], [B, 2], [C, 3] } } |
The Remove()
method returns true
if the key is successfully removed from the dictionary and false
if the key is not found in the dictionary, as the following example illustrates.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3}, {"D", 4} }; var keyToRemove = "D"; if (dict.Remove(keyToRemove)) { Console.WriteLine("Key removed from the Dictionary"); } else { Console.WriteLine("Dictionary doesn't contain the Key"); } Console.WriteLine(String.Join(", ", dict)); // [A, 1], [B, 2], [C, 3] } } |
2. Using LINQ
To avoid any modifications to the existing dictionary, you can use LINQ to construct a new dictionary instance without the desired key-value pairs. The following code example shows how to remove the specified collection of keys from a dictionary.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3}, {"D", 4} }; HashSet<string> keysToRemove = new HashSet<string> {"A", "C"}; var filteredDict = dict.Where(kvp => !keysToRemove.Contains(kvp.Key)) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); Console.WriteLine(String.Join(", ", filteredDict)); // [B, 2], [D, 4] } } |
That’s all about removing a key from 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 :)