Let us say, we have a Dictionary that contains,
As Key and Value pair.
Now, if you want to remove the entries from a Dictionary, Remove() and Clear() Method can be used.
Let us look at the Remove() Method first.
The Remove() Method can be used to remove an item from the Dictionary.
Let us say, we want to remove the entry where the Key is 5 and Value is Is a Number.
using System.Collections.Generic; public class MyApplication { public static void Main(string[] args) { Dictionary<object, string> x = new Dictionary<object, string>() { { 5, "Is a Number" }, { "John", "Is a Name" }, { "C#", "Is a Language"} }; x.Remove(5); foreach (KeyValuePair<object, string> i in x) { System.Console.WriteLine("The key is : "+i.Key+" and the value is : "+i.Value); } } }
So, in the above code we have created a Dictionary using braces {} and Key and Value pairs.
Dictionary<object, string> x = new Dictionary<object, string>() { { 5, "Is a Number" }, { "John", "Is a Name" }, { "C#", "Is a Language"} };
And initialised to the variable x.
Now, we are supposed to delete the value of the Key, 5.
So, we have used the below way to update it.
x.Remove(5);
And the entry for the Key 5 is deleted for the Dictionary.
And we get the below output,
The Clear() Method can be used to remove all the elements from the Dictionary.
using System.Collections.Generic; public class MyApplication { public static void Main(string[] args) { Dictionary<object, string> x = new Dictionary<object, string>() { { 5, "Is a Number" }, { "John", "Is a Name" }, { "C#", "Is a Language"} }; x.Clear(); foreach (KeyValuePair<object, string> i in x) { System.Console.WriteLine("The key is : "+i.Key+" and the value is : "+i.Value); } } }
So, in the above code we have created a Dictionary using braces {} and Key and Value pairs.
Dictionary<object, string> x = new Dictionary<object, string>() { { 5, "Is a Number" }, { "John", "Is a Name" }, { "C#", "Is a Language"} };
And initialised to the variable x.
And we have used the Clear() method to remove all the elements from the Dictionary.
x.Clear()
And the print statement, prints an empty Dictionary.