Dictionary remove range
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 44 45 46 47 48 49 50 51 | class Program { static void Main(string[] args) { //initialize a dictionary with keys and values. Dictionary<int, string> birds = new Dictionary<int, string>() { {1,"Musk Lorikeet"}, {2,"Papuan Lorikeet"}, {3,"Bluebonnet"}, {4,"Crimson Rosella"}, {5,"Mulga Parrot"}, {6,"Regent Parrot"} }; Console.WriteLine("dictionary keys and values.........."); foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } int rangeStart = 2; int rangeEnd = 4; List<int> keysList = new List<int>(); for (int i = rangeStart; i <= rangeEnd; i++) { //zero based index on dictionary. int keysToRemove = birds.Keys.ElementAt(i); keysList.Add(keysToRemove); } Console.WriteLine("\nremoving keys from dictionary index range 2 to 4"); foreach (int key in keysList) { //remove element from dictionary. birds.Remove(key); Console.WriteLine("key [" + key + "] removed from dictionary"); } Console.WriteLine("\ndictionary after removing elements index range 2 to 4 .........."); foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } Console.ReadLine(); } } |
Output:

How to remove range of items from a Dictionary in C#