Updating Dictionary elements while iterating

As we know we can't update any dictionary collection element if we are iterating them using foreach loop.
For example, we could iterate Dictionary using KeyValuePair in foreach loop but we can't modify them because as per MSDN: "If the iteration variable is a value type, it is effectively a read-only variable that cannot be modified". So being our iteration variable 'KeyValuePair<TKey, TValue> as a struct type (value type) here, it can't be updated.
 
But what if we want to iterate the entire dictionary and at the same time also we have a need to modify the Dictionary Elements.

Let's see how we can do this:


            Dictionary<int, string> ProductCollection = new Dictionary<int, string>();
           
            ProductCollection.Add(1, "AAAAAAAAAAAAAA");
            ProductCollection.Add(4, "BBBBBBBBBBBBBB");
            ProductCollection.Add(7, "CCCCCCCCCCCCCC");

            //Iterating entire ProductCollection but we can't update Dictionary element in foreach loop
            foreach (KeyValuePair<int, string> item in ProductCollection)
            {
                Console.WriteLine(item.Key + "\t" + item.Value);
            }

            //Grab all the Keys and put it in a list
            List<int> ids = ProductCollection.Keys.ToList();

            //Iterate all the Dictionary elements through their keys and modify the dictionary elements
            foreach (int idKey in ids)
            {
                ProductCollection[idKey] += "ChangedBy"+idKey.ToString();
            }


            foreach (KeyValuePair<int, string> item in ProductCollection)
            {
                Console.WriteLine(  item.Key + "\t"+ item.Value);
            }


Ebook Download
View all
Learn
View all