Michael K.
Michael K.

Reputation: 463

Remove empty columns from a DataTable

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.

Upvotes: 1

Views: 3818

Answers (1)

Kilazur
Kilazur

Reputation: 3188

My humble guess:

As long as the list isn't finalized (with ToList() for example), you are indeed working on it, and never actually making a copy.

IEnumerable<DataColumn> queriableColumms = data.Columns.Cast<DataColumn>().AsQueryable();

We see here that you use data to produce a Queryable, not an independent list.

var toBeRemoved = from DataColumn column in queriableColumms
                where data.AsEnumerable().All(row => row.IsNull(column))
                select column;

Here as well, you're using LinqToSQL, and not finalizing the list.

So when you call toBeRemoved, you call the query's result, thus are still using the original source, data.

Try using toBeRemoved.ToList(), and doing your loop on that.


Actually, I think the problem may lie somewhere else since you say your exception happens when you start your loop on toBeRemoved and not when you actually try to delete an item, but I'll edit later if this solution doesn't work.

Upvotes: 1

Related Questions