I like to iterate back using a for loop, but it can get tedious compared to foreach . One solution that I like is to create an enumerator that moves the list back. You can implement this as an extension method on an ArrayList or List<T> . The implementation for ArrayList below.
public static IEnumerable GetRemoveSafeEnumerator(this ArrayList list) { for (int i = list.Count - 1; i >= 0; i--) { // Reset the value of i if it is invalid. // This occurs when more than one item // is removed from the list during the enumeration. if (i >= list.Count) { if (list.Count == 0) yield break; i = list.Count - 1; } yield return list[i]; } }
The implementation for List<T> similar.
public static IEnumerable<T> GetRemoveSafeEnumerator<T>(this List<T> list) { for (int i = list.Count - 1; i >= 0; i--) { // Reset the value of i if it is invalid. // This occurs when more than one item // is removed from the list during the enumeration. if (i >= list.Count) { if (list.Count == 0) yield break; i = list.Count - 1; } yield return list[i]; } }
The following example uses an enumerator to remove all even integers from an ArrayList .
ArrayList list = new ArrayList() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; foreach (int item in list.GetRemoveSafeEnumerator()) { if (item % 2 == 0) list.Remove(item); }
Joe B Jan 25 2018-11-22T00: 00Z
source share