Advertisements

Archive

Posts Tagged ‘add element while iterating’

Modify Collection while Iterating C#

May 10, 2017 1 comment

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