C# C# Console Application

How to remove first element from Dictionary in C#2 min read

Dictionary remove first element

C# Code:




This C# program creates a dictionary called “birds” with keys and values representing different species of birds. The program then iterates through the dictionary and prints out the key and value of each entry.

Then, the program uses the Remove() method to remove the first key-value pair in the dictionary. The output will be the birds dictionary keys and values without the first key-value pair from the initial dictionary.

Certainly, here’s an explanation of the code:

  1. The program starts by creating a new dictionary called “birds” with 5 key-value pairs. The keys are integers and the values are strings representing the names of different birds.
  2. Next, the program uses a foreach loop to iterate through the “birds” dictionary and print out the key and value of each entry. The foreach loop uses the KeyValuePair<int, string> type, which is a built-in type in C# that allows you to loop through a dictionary.
  3. The program then calls the Remove() method on the “birds” dictionary and passing in birds.Keys.First() as the argument. This will remove the first key-value pair in the dictionary, which is the key-value pair where the key is 1 and the value is “Tundra Swan”.
  4. Finally, the program uses another foreach loop to iterate through the “birds” dictionary and print out the key and value of each remaining entry,

It’s worth mentioning that there is also an alternate way which is birds.Remove(birds.Keys.FirstOrDefault()); that is commented in the code as well and it is useful when you want to delete the first item in dictionary if there is one exist otherwise it will not do anything.

It’s also worth noting that C# provides the Dictionary<TKey,TValue>.Remove(TKey key) method that removes the element with the specified key from the Dictionary<TKey,TValue> and it will return a bool that indicates whether the element was found and removed or not.

Output:

How to remove first element from Dictionary in C#
How to remove first element from Dictionary in C#

Leave a Comment