从For循环中删除一条记录。 [英] delete one record from For loop.
问题描述
你好团队,
我有一个for循环
Hi team,
I have a for loop
for (int numberOfCount = 0; numberOfCount < singleCellRecords.Count; numberOfCount--)
{}
我在singleCellRecords.Count中获取值。现在我想从singleCellRecords.Count中删除一条记录。
怎么可能在for循环中。
我错了。请给我建议。
谢谢
Harshal
I am getting the value in singleCellRecords.Count.Now i want to delete one record from singleCellRecords.Count .
how could it possible in for loop.
I am getting somewhere wrong.please Advice.
Thanks
Harshal
推荐答案
尝试如下
try like below
for (int i = singleCellRecords.Count - 1; i >= 0; i--)
{
if(put your condtion to find the record you need)
{
singleCellRecords.RemoveAt(i);
break; // call the break method
}
}
从List<>等内容中删除时你不能使用 foreach
循环或者你会得到一个异常
When deleting from things like a List<> you cannot use the foreach
loop or you will get an exception
集合被修改;枚举操作可能无法执行。
Collection was modified; enumeration operation may not execute.
但是你可以使用普通的来获取
-loop
例如,如果我设置了一个字符串列表,用于测试
You can however use an ordinary for
-loop
For example if I set up a list of string for testing
List<string> SL = new List<string>();
for (int i = 0; i < 10; i++)
SL.Add(i.ToString());
我可以这样做
I can do this
for(int j = SL.Count - 1; j >=0; j--)
{
if (j == 5)
SL.Remove(SL[j]);
}
请注意,我已经从列表的结尾开始并向后移动到开头 - 这样你总能知道它的位置你尚未查看的项目 - 列表后面的项目会在项目被删除时移动索引
Note that I've started at the "end" of the list and moved backwards to the beginning - that way you always know the position of the items you haven't looked at yet - it's the one's later in the list that will "move" index when an item is deleted
这篇关于从For循环中删除一条记录。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!