Donate

How To Iterate Or Loop Through A C# Dictionary And Update It's Value

Hello,

Most of us C# developers are working on Dictionaries to store multiple sets of data with unique keys. And in times that we need to modify our logic with the Dictionary object involved, we normally do that using looping construct. Given a simple Dictionary object below with int as key and string as value.
Dictionary<int,string> styledLines = new Dictionary<int,string>();
We may thought that looping through this object with the code presented below may work. However, when running your app, this will cause a "Collection was modified; enumeration operation may not execute" issue. It's because we are using the collection's key directly.
foreach (var kvp in styledLines)
{
   styledLines[kvp.key] = $"Series#{seriesNum}";
}
To fix that we have a couple of options. Given that our key is an integer type with values in sequential order such as 0...1000, we could use for loop to change the values such as below.
var startIndex = styledLines.Keys.First();
var endIndex = styledLines.Keys.Last();
for (int i = startIndex; i <= endIndex; i++)
{
	styledLines[i] = $"Series# {seriesNum}";
}
The preferred solution which is the code below, is to grab the Dictionary object's keys and store them to a List object and then use foreach to traverse the keys which will then be used by the Dictionary object. This will prevent the "Collection was modified; enumeration operation may not execute" error since we don't directly interface with the Dictionary keys. But instead use the keys stored from the List object.
List<int> styleKeys = new List<int>(styledLines.Keys);
foreach (var key in styleKeys)
{
    styledLines[key] = $"Series# {seriesNum}";
}


Cheers!

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations