Reputation: 187
I am trying to delete datacolumns from a datatable: I get the following error:
System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'
when i try to execute the following code:
foreach (DataColumn col in csvData.Columns)
{
if (col.ColumnName.Contains("Column"))
{
csvData.Columns.Remove(col);
}
}
I do understand the error, since i is true that i am modifying the collection. I just don't know how to handle it. Anyone have an idea? I tried rapping it in a try/catch, but that only removes the first column containing column.
Upvotes: 0
Views: 600
Reputation: 23228
This code should solve the issue, by using a for
loop and go from upperbound to 0
for (int i = csvData.Columns.Count - 1; i >= 0; i--)
{
DataColumn dc = csvData.Columns[i];
if (dc.ColumnName.Contains("Column"))
{
csvData.Columns.Remove(dc);
}
}
Upvotes: 1