如何在 C# 中迭代时修改或删除可枚举集合中的项目 [英] How to modify or delete items from an enumerable collection while iterating through it in C#
问题描述
我必须从数据表中删除一些行.我听说在迭代时更改集合是不行的.因此,我应该先遍历数据表并添加列表中的所有行,然后遍历列表并标记用于删除的行.造成这种情况的原因是什么,我有哪些替代方案(而不是使用行列表)?
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)?.
推荐答案
如果您使用简单的 for
循环,您可以从集合中删除元素.
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屋!