如何以编程方式从DataTable中删除DataColumn [英] How to remove DataColumn from DataTable programmatically

查看:210
本文介绍了如何以编程方式从DataTable中删除DataColumn的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码

foreach (DataColumn dataTableCol in this.dataTable.Columns)
            {
                bool columnFound = false;
                foreach (GRTColumnView uiColumn in descriptor.UIColumns)
                {
                    if (dataTableCol.ColumnName.Equals(uiColumn.Name))
                    {
                        columnFound = true;
                        break;
                    }
                }

                if (!columnFound)
                {
                    if (this.dataTable.Columns.Contains(dataTableCol.ColumnName))
                        this.dataTable.Columns.Remove(dataTableCol.ColumnName);
                }

            }

我想删除一些东西

当我运行上述程序时,我得到了

When I run the above program, I get

在修改集合后可能不会执行迭代

集合为已修改-Coz删除必须已被击中

"Collection was modified" - Coz the remove must have been hit

那么实现这种目标的方法是什么?

我能想到的是记下要删除的所有东西,然后

What I can think of is make a note of all the "things" to remove and then

foreach( aThing in all_things_to_remove)
     remove_from_collection(aThing)

但是上面似乎没有对我来说是个好方法,因为我必须执行另一个循环并使用额外的内存

But above doesn't seem a good way to me, as I have to do another looping and am using extra memory

推荐答案

在这种情况下,遍历一个包含几列的小集合,您可以创建一个新的集合(通过 ToList()),这样您就不必遍历正在修改的同一集合:

In this specific case, where you're looping through a small collection containing a few columns, you can just create a new collection (via ToList()), so that you're not iterating over the same collection you're modifying:

foreach (var dataTableCol in dataTable.Columns.Cast<DataColumn>().ToList())
{
    ...

    dataTable.Columns.Remove(dataTableCol.ColumnName);
}

推荐的方法,特别是如果集合很大的情况,是向后枚举:

The recommended way, especially if the collection is large, is to enumerate backwards:

for (var i = dataTable.Columns.Count - 1; i >= 0; i--)
{
    ...

    dataTable.Columns.Remove(dataTable.Columns[i].ColumnName);
}

这篇关于如何以编程方式从DataTable中删除DataColumn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆