Dictionary remove by condition
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 36 37 38 39 40 41 42 43 |
class Program { static void Main(string[] args) { //initialize a dictionary with keys and values. Dictionary<int, string> birds = new Dictionary<int, string>() { {1,"Squirrel Cuckoo"}, {2,"Golden Oriole"}, {3,"Golden Nightjar"}, {4,"Northern Oriole"}, {5,"Warbling Vireo"} }; Console.WriteLine( "dictionary keys and values.........."); foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } int[] keysToDelete = birds.Where(x => x.Value.EndsWith("Oriole")).Select(x => x.Key).ToArray(); //another condition to remove dictionary elements. //int[] keysToDelete = birds.Keys.Where(x => x < 3).ToArray(); Console.WriteLine("\nremoving elements from dictionary"); foreach (int key in keysToDelete) { birds.Remove(key); Console.WriteLine("key [" + key + "] removed from dictionary"); } Console.WriteLine("\nelemetns removed which value ends with [Oriole].........."); Console.WriteLine("dictionary keys and values after remove.........."); foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } Console.ReadLine(); } } |
Output: