How To Remove All Elements From A Dictionary In C#

C# Dictionary class is a generic collection of a (key, value) pair. Dictionary<TKey,TValue> class and its methods can be used to add, update, find and remove elements from the collection. Dictionary.Remove() and Dictionary.Clear() methods are used to remove elements of the collection. The Remove method removes elements matching with the key passed in the Remove method. The Clear method removes all elements from the dictionary.

Let's create a simple application. Create a .NET Framework or .NET Core console application using C# template. Make sure to import the System.Collections.Generic namespace in your application.
 
In the main method, add the following code. The following code snippet creates a Dictionary and adds an item to it by using the Add method.
  1. Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();  
  2. AuthorList.Add("Mahesh Chand", 35);  
  3. AuthorList.Add("Mike Gold", 25);
  4. AuthorList.Add("Praveen Kumar", 29);
  5. AuthorList.Add("Raj Beniwal", 21);
  6. AuthorList.Add("Dinesh Beniwal", 84);
The Remove method removes an item with the specified key from the collection. The following code snippet removes an item.
  1. // Remove item with key = 'Mahesh Chand'  
  2. AuthorList.Remove("Mahesh Chand");   
Output
 
 
 
The Clear method removes all elelemts of the collection. The following code snippet removes all elements by calling the Clear method.
  1. // Remove all items  
  2. AuthorList.Clear(); 


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.