0

I want to delete all datatables in a dataset apart from one. I've tried this :-

        foreach (DataTable table in DtSet.Tables)
        {
            if (table.TableName != "tblAccounts")
            {
                DtSet.Tables.Remove(table);
            }
        }  

but I get a

"Collection was modified; enumeration operation may not execute." error

.

madth3
  • 7,275
  • 12
  • 50
  • 74
bd528
  • 886
  • 2
  • 11
  • 29

3 Answers3

3

You cannot modify a collection during enumeration. But you could use a for-loop:

for (int i = DtSet.Tables.Count - 1; i >= 0; i--)
{
    var table = DtSet.Tables[i];
    if (table.TableName != "tblAccounts")
        DtSet.Tables.Remove(table);
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

Just throwing this out there as it is untested but has no loops.

var accounts = DtSet.Tables["tblAccounts"];
DtSet.Tables.Clear();
DtSet.Tables.Add(accounts);
Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
1

You'll get this anytime you try to modify a collection during a foreach. It has to do with the way the collection is iterated through.

You can do it a couple ways - one way is to determine the tables you want to remove while you're in the loop, then afterward, go back and remove them. I think the following will work:

var tablesToRemove = new List<DataTable>();
foreach (DataTable table in DtSet.Tables)
{
    if (table.TableName != "tblAccounts")
    {
        tablesToRemove.Add(table);
    }
}

foreach (DataTable table in tablesToRemove)
{
    DtSet.Tables.Remove(table);
}
Joe Enos
  • 39,478
  • 11
  • 80
  • 136
  • Tim's answer will definitely run faster since you're only looping through once. This way gets you the benefit of being able to debug and see exactly which tables you'll be removing before removing them. But I'd probably do it Tim's way. – Joe Enos Jan 14 '13 at 22:52