Advertisements
Home > ASP.NET > Modify Collection while Iterating C#

Modify Collection while Iterating C#


The general rule is that you can’t modify a collection/array/list while iterating over it.

If you are trying to modify loop while iterating you will get following error message

List strList = new List();

strList.Add(“1”);
strList.Add(“2”);
strList.Add(“3”);
strList.Add(“4”);

foreach(string str in strList)
{
strList.Add(“test”);
}

Error:

System.InvalidOperationException: Collection was modified; 
enumeration operation may not execute.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at Rextester.Program.Main(String[] args)

Here is the simple solution

int listLength = strList.Count();

for(int i=0; i<listLength; i++)
{

//Add New Element
if(i == 0)//Some codition when you want to add new element to list/array
{
listLength++;
strList.Add(“5”);
}

Console.WriteLine(strList[i]);
}

Hope it helps !

Advertisements
  1. May 10, 2017 at 9:11 pm

    Use more button for sharing this post to WhatsApp and Skype

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: