When an element is deleted in foreach, Each deletion changes the size of the Set and the value of the element index. An exception occurs when an element is deleted in foreach.
The solution is to use a for loop and traverse from the end to the header.
For traversal from start to end, you will delete only half of the elements. As follows:
namespace CSharpLearning{ using System; using System.Collections.Generic; /// /// The program. /// public class Program { /// /// The main. /// public static void Main() { List
integers = new List
(); for (int i = 0; i < 100; i++) { integers.Add(i); } for (int i = 0; i < integers.Count; i++) { integers.Remove(integers[i]); } Console.WriteLine(integers.Count); } }}// Output: 50
The correct method is to traverse from the end to the header, as shown below:
namespace CSharpLearning{ using System; using System.Collections.Generic; /// /// The program. /// public class Program { /// /// The main. /// public static void Main() { List
integers = new List
(); for (int i = 0; i < 100; i++) { integers.Add(i); } for (int i = integers.Count - 1; i >= 0; i--) { integers.Remove(integers[i]); } Console.WriteLine(integers.Count); } }}// Output: 0