j. Doe j. Doe - 2 months ago 14
C# Question

Looping through a dynamic List of objects

I'm trying to implement a snippet where we can loop through a dynamic list of objects.

using System;
using System.Collections.Generic;

public class Program
{
public static void Main()
{
var l = new List<int>();
l.Add(1);
l.Add(2);
l.Add(3);
l.Add(4);

foreach(var i in l){
Console.WriteLine(i);
if(i==3){
l.Add(5);
}

}

}

}


This is throwing below run time error.

1
2
3
Run-time exception (line 15): Collection was modified; enumeration operation may not execute.

Stack Trace:

[System.InvalidOperationException: Collection was modified; enumeration operation may not execute.]
at Program.Main(): line 15


Any help is appreciated. Thanks.

Answer

This can be achieved by replacing foreach with for loop

for (var i = 0; i < l.Count; i++)
{
     Console.WriteLine(l[i]);
     if (l[i] == 3)
     {
        l.Add(5);
     }
}
Comments