[英]C# Best way to remove all datatables apart from one
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
错误
. 。
You cannot modify a collection during enumeration. 您无法在枚举期间修改集合。 But you could use a
for-loop
: 但是您可以使用
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);
}
You'll get this anytime you try to modify a collection during a foreach
. 在
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);
}
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.