Home
Search
C# foreach List: Loop Over List ElementsUse the foreach loop on a List. Understand the Collection was modified exception.
Foreach, List. With foreach we can loop over the items in a List. This works just like the for-loop, but with simpler syntax. But there is a limitation.
List
An exception. We cannot modify a List while we use foreach on it. A "Collection was modified" exception will be thrown. Foreach requires the collection not change under it.
Required output. Consider a list that has 3 elements. In our foreach-loop, we want to safely iterate over the 3 elements in order.
List contents:
10, 100, -1 Iterations: 10 100 -1
For each example. This example has 2 parts. It shows an exception that can occur when using for each on a List. In our code, it is best to avoid this exception.
Part 1 In the first foreach loop, we correctly loop over the ints in the List.
Foreach
Part 2 In the second foreach loop, we create an error by trying to add an item to the List while in a foreach.
Exception
Important We must not modify a List inside a foreach-loop on that List. Other Lists can still be modified though.
C# program that uses foreach on List
using System; using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int>(); list.Add(10); list.Add(100); list.Add(-1); // Part 1: we can loop over list items with foreach. foreach (int value in list) { Console.WriteLine(value); } Console.WriteLine("::DONE WITH PART 1::"); // Part 2: this will cause an exception. foreach (int value in list) { list.Add(0); } } }
10 100 -1 ::DONE WITH PART 1:: Unhandled Exception: 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 Program.Main() in...
A solution. How can we modify a List while looping over it? There is a solution: we can use a for-loop. The for-loop has no "Collection was modified" limitation.
For
A summary. The foreach-loop is a way to simplify syntax in programs. But it is not always perfect—it has a limitation that we cannot modify an underlying collection.
Home
© 2007-2021 sam allen.
see site info on the changelog.