Although the iterator variable in a foreach
loop is immutable, I am able to modify my collection in the example below if I use Where()
to do the modification:
static void Main(string[] args)
{
var list = new List<int> { 1, 2, 3, 4 };
foreach (var listElement in list)
{
Console.WriteLine(listElement + " ");
list = list.Where(x => x != listElement).ToList();
}
Console.WriteLine("Count: " + list.Count);
}
Output:
1
2
3
4
Count: 0
Could someone please explain this behavior?