如何修改或同时通过在C#中的迭代可枚举集合删除项目 [英] How to modify or delete items from an enumerable collection while iterating through it in C#
问题描述
我不得不从数据表中删除某些行。我听说,这是不正常,同时通过其迭代改变的集合。因此,而不是一个for循环中,我检查,如果某行符合删除要求,然后将其标记为删除了,我应该先通过数据表进行迭代,并添加所有行的列表中,然后通过列表和标记迭代行的删除。什么是这方面的原因,和我有什么替代品(而不是使用排列表我的意思)?
I have to delete some rows from a data table. I've heard that it is not ok to change a collection while iterating through it. So instead of a for loop in which I check if a row meets the demands for deletion and then mark it as deleted, I should first iterate through the data table and add all of the rows in a list, then iterate through the list and mark the rows for deletions. What are the reasons for this, and what alternatives do I have (instead of using the rows list I mean)?.
推荐答案
您可以从一个集合,如果你用一个简单的为
循环删除元素。
You can remove elements from a collection if you use a simple for
loop.
在这个例子看看:
var l = new List<int>();
l.Add(0);
l.Add(1);
l.Add(2);
l.Add(3);
l.Add(4);
l.Add(5);
l.Add(6);
for (int i = 0; i < l.Count; i++)
{
if (l[i] % 2 == 0)
{
l.RemoveAt(i);
i--;
}
}
foreach (var i in l)
{
Console.WriteLine(i);
}
这篇关于如何修改或同时通过在C#中的迭代可枚举集合删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!