how to remove from Dictionary while iterating over it

Since we’re in C#/.NET and not in Java, we don’t have Iterator.remove() (I really miss that method at times), and since we’re operating on Dictionary instead of List, we can’t use a RemoveAll instance method with a Predicate delegate.

However, as it does with many, many other questions about using and handling generic collections, the good ol’ Power Collections project comes to the rescue. Specifically, the Algorithms.RemoveWhere method.

Ok, technically we’re not iterating over it (at least not in our code), but it keeps us from having to manually do the whole “store the keys to remove in a List and then iterate over that list to .Remove() from the Dictionary”

This also shows off the super-spiffy Algorithms.ToString method – incredibly useful stuff!

The output:

Original: {0->a, 1->b, 2->c, 3->d, 4->e, 5->f, 6->g, 7->h, 8->i, 9->j}
Kept:     {1->b, 3->d, 5->f, 7->h, 9->j}
Removed:  {[0, a],[2, c],[4, e],[6, g],[8, i]}

        static void Main(string[] args)
            Dictionary<int, char> dict = new Dictionary<int, char>();
            for (int i = 0; i < 10; i++)
                dict.Add(i, Convert.ToChar(i + 'a'));
            Console.WriteLine("Original: {0}", Algorithms.ToString(dict));
            ICollection<KeyValuePair<int, char>> removed =
                Algorithms.RemoveWhere(dict, delegate(KeyValuePair<int, char> pair)
                return pair.Key % 2 == 0;
            Console.WriteLine("Kept:     {0}", Algorithms.ToString(dict));
            Console.WriteLine("Removed:  {0}", Algorithms.ToString(removed));