Dictionary remove first element
C# Code:
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 32 33 34 35 |
class Program { static void Main(string[] args) { //initialize a dictionary with keys and values. Dictionary<int, string> birds = new Dictionary<int, string>() { {1,"Tundra Swan"}, {2,"Hawaiian Goose"}, {3,"Egyptian Goose"}, {4,"Orinoco Goose"}, {5,"Andean Goose"} }; Console.WriteLine( "dictionary keys and values.........."); foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } //this line remove/delete dictionary first keyvaluepair. birds.Remove(birds.Keys.First()); //alternate way to remove dictionary first element. //birds.Remove(birds.Keys.FirstOrDefault()); Console.WriteLine("\ndictionary keys and values after remove first pair....."); foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } Console.ReadLine(); } } |
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:
- 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.
- Next, the program uses a
foreach
loop to iterate through the “birds” dictionary and print out the key and value of each entry. Theforeach
loop uses theKeyValuePair<int, string>
type, which is a built-in type in C# that allows you to loop through a dictionary. - The program then calls the
Remove()
method on the “birds” dictionary and passing inbirds.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”. - 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: