如何以编程方式从 DataTable 中删除 DataColumn [英] How to remove DataColumn from DataTable programmatically
问题描述
我有一个代码
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);
}
}
如果在另一个集合中找不到某些东西",我想从集合中删除它们.
I want to remove some "things" from collection if they aren't found in another collection.
当我运行上面的程序时,我得到
When I run the above program, I get
由于集合被修改,迭代可能无法执行
集合已修改" - 因为删除必须被点击
"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屋!