简体   繁体   English

C#删除除一个以外的所有数据表的最佳方法

[英]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.

相关问题 除了 T4 [暂停] 从模板文件生成 C# 中的代码文件的最佳方法是什么 - What is the best way to generate code files in C# from template file apart from T4 [on hold] 在 C# 中将列表中的所有项目移动一个 position 的最佳方法 - Best way to move all items in a list by one position in C# 从C#中的字符串中获取所有类似@ * @的单词的最佳方法 - Best way to get all words like @*@ from a string in C# 删除C#中重复代码的最佳方法 - Best way to remove duplicated code in C# 有没有一种简单的方法可以从 C# 中的 MongoDB 集合中删除所有数据? - Is there an easy way to remove all data from MongoDB collection in C#? C#将数据与数据库分开存储 - C# Store data apart from Database C#从SQL创建数据表的简单拖放方式? - C# Easy drag and drop way to create DataTables from SQL? 如何在MongoDB中更新文档并更改除C#中的from_id以外的所有属性 - How do I update a document in MongoDB & change all properties apart from_id in C# 在C#Win中从字符串中删除字符的最佳方法。 形成 - Best way to remove characters from string in c# win. form 在 c# 中上传时从图像中删除 Exif 数据的最佳方法是什么 - What is the best way to remove Exif data from Images while uploading in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM