Dictionary Clear() Method: .Net framework dictionary Clear() method allow us to remove all keys and values from the Dictionary<TKey, TValue>. this Dictionary<TKey, TValue>.Clear() method exists under System.Collections.Generic namespace. this method has no optional or required parameter.
the Clear() method implements as ICollection<T>.Clear() and IDictionary.Clear(). this method set the Count property value to 0 (zero) but the Capacity remains unchanged.
the following c# example code demonstrate us how can we remove all elements from dictionary programmatically at run time in an console application.
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 30 31 | class Program { static void Main(string[] args) { Dictionary<string, string> colors = new Dictionary<string, string>(); colors.Add("BlanchedAlmond", "#FFEBCD"); colors.Add("Brown", "#A52A2A"); colors.Add("Cornsilk", "#FFF8DC"); colors.Add("FireBrick", "#B22222"); colors.Add("GreenYellow", "#ADFF2F"); Console.WriteLine("Dictionary Keys..."); foreach (string color in colors.Keys) { Console.WriteLine(color ); } //Clear() method remove all keys and values from the Dictionary. colors.Clear(); Console.WriteLine("\nAfter Call Clear() Method. Dictionary Keys..."); foreach (string color in colors.Keys) { Console.WriteLine(color ); } Console.ReadLine(); } } |
Output: