Jack Kada Jack Kada - 1 year ago 98
C# Question

Safely Removing DataRow In ForEach

I don't understand why this code does not work.

foreach (DataRow dataRow in dataTable.Rows)
if (true)

Answer Source

Most collections in .NET don't allow you to change the contents of the collection while you're iterating over it. From the docs for IEnumerator:

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and the next call to MoveNext or Reset throws an InvalidOperationException. If the collection is modified between MoveNext and Current, Current returns the element that it is set to, even if the enumerator is already invalidated.

The best solution is usually to create a separate collection (e.g. a List<DataRow>) of items you want to remove, and then remove them after you've finished iterating.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download