How to remove DataColumn from DataTable programmatically

SimpleGuy picture SimpleGuy · Jan 14, 2015 · Viewed 11.6k times · Source

I have a code

foreach (DataColumn dataTableCol in this.dataTable.Columns)
            {
                bool columnFound = false;
                foreach (GRTColumnView uiColumn in descriptor.UIColumns)
                {
                    if (dataTableCol.ColumnName.Equals(uiColumn.Name))
                    {
                        columnFound = true;
                        break;
                    }
                }

                if (!columnFound)
                {
                    if (this.dataTable.Columns.Contains(dataTableCol.ColumnName))
                        this.dataTable.Columns.Remove(dataTableCol.ColumnName);
                }

            }

I want to remove some "things" from collection if they aren't found in another collection.

When I run the above program, I get

Iteration may not execute as collection was modified

"Collection was modified" - Coz the remove must have been hit

What is the way to achieve such a thing then ?

What I can think of is make a note of all the "things" to remove and then

foreach( aThing in all_things_to_remove)
     remove_from_collection(aThing)

But above doesn't seem a good way to me, as I have to do another looping and am using extra memory

Answer

Grant Winney picture Grant Winney · Jan 14, 2015

In this specific case, where you're looping through a small collection containing a few columns, you can just create a new collection (via ToList()), so that you're not iterating over the same collection you're modifying:

foreach (var dataTableCol in dataTable.Columns.Cast<DataColumn>().ToList())
{
    ...

    dataTable.Columns.Remove(dataTableCol.ColumnName);
}

The recommended way, especially if the collection is large, is to enumerate backwards:

for (var i = dataTable.Columns.Count - 1; i >= 0; i--)
{
    ...

    dataTable.Columns.Remove(dataTable.Columns[i].ColumnName);
}