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.
- Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();
- AuthorList.Add("Mahesh Chand", 35);
- AuthorList.Add("Mike Gold", 25);
- AuthorList.Add("Praveen Kumar", 29);
- AuthorList.Add("Raj Beniwal", 21);
- 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.
-
- 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.