I want to remove all empty columns from a DataTable. I created a list of all columns that consist of only empty rows, and then delete them.
It doesn't work because of a System.InvalidOperationException. The exception claims I try to edit the collection that I enumerate, something I don't understand since I think I copied that collection.
private DataTable data;
public void removeEmptyColoums()
{
// Get all empty coloums
IEnumerable<DataColumn> queriableColumms = data.Columns.Cast<DataColumn>().AsQueryable();
var toBeRemoved = from DataColumn column in queriableColumms
where data.AsEnumerable().All(row => row.IsNull(column))
select column;
// Delete them
foreach(DataColumn column in toBeRemoved) // Exception thrown here
{
data.Columns.Remove(column);
}
}
I'm not sure about the. AsQueryable and .Cast calls either.
foreach(DataColumn column in toBeRemoved.ToArray()var[] toBeRemovedand then perform iteration offoreachloop on it