foreach遍历删除 List 元素时为什么会报错或漏删?
使用 foreach 循环直接删除 list 中的元素会抛出 invalidoperationexception,因为该集合在枚举期间被修改了。如果改用 for 循环从前往后遍历并删除,会导致索引错位从而“漏删”相邻元素。这是因为每次调用 removeat 都会使后续元素的索引前移一位,而循环变量 i 依然递增,导致跳过了紧跟在被删除元素之后的那个元素。

using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// 错误做法:从前往后 for 循环
for (int i = 0; i <p>运行上述代码,输出结果为 <code>1, 2, 4, 5</code>。可以看到数字 <code>3</code> 被成功移除,但原本在 <code>3</code> 后面的 <code>4</code> 并没有被检查到(如果 <code>4</code> 也满足条件的话就会被漏掉)。这是因为当 <code>i=2</code> 时删除了 <code>3</code>,列表变为 <code>{1, 2, 4, 5}</code>,此时 <code>4</code> 的索引变成了 <code>2</code>。下一次循环 <code>i</code> 变为 <code>3</code>,程序直接去检查索引 <code>3</code> 处的 <code>5</code>,从而跳过了 <code>4</code>。</p>
<h2>如何正确地在 <code>for</code> 循环中删除 <code>List<t></t></code> 元素?</h2>
<p>要解决 <code>for</code> 循环删除导致的漏删问题,必须采用<strong>倒序遍历</strong>的方式。从列表的最后一个元素开始向前遍历,这样在删除当前元素时,不会影响尚未遍历到的前面元素的索引位置。</p>
<p><img src="https://img.php.cn/upload/article/001/431/639/179530939564442.png?x-oss-process=image/resize,p_40" alt="C#for循环删除List元素时,为什么会漏删?"></p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill2795" title="C#"><img
src="https://img.php.cn/upload/skill/000/000/081/178936933912641.jpg" alt="C#" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill2795" title="C#" class="overflowclass">C#</a>
<p class="overflowclass">"避开 C# 常见错误——空陷阱、异步陷阱、LINQ 陷阱及资源泄漏。"</p>
</div>
<a rel="nofollow" href="/xiazai/skill2795" title="C#" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<pre class="brush:php;toolbar:false;">using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
// 正确做法:倒序 for 循环
for (int i = numbers.Count - 1; i >= 0; i--) {
if (numbers[i] % 2 == 0) { // 删除偶数
numbers.RemoveAt(i);
}
}
Console.WriteLine(string.Join(", ", numbers));
}
}</int></int>
运行上述代码,输出结果为 1, 3, 5。所有偶数都被正确移除。因为是从后往前删,删除索引 i 的元素只影响索引大于 i 的元素,而这些元素已经被处理过了,所以前面的元素索引保持不变,逻辑安全。
基于程序中某个输入、条件或结果的具体问题:为什么 RemoveAll 是更优解?
在实际开发中,除了手动控制 for 循环,C# 提供了 List 方法,它内部已经处理了索引偏移的问题,是删除符合条件元素的推荐方式。针对上面倒序遍历的代码,我们可以直接用一行代码替代整个循环。
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
// 最优做法:使用 RemoveAll
int removedCount = numbers.RemoveAll(n => n % 2 == 0);
Console.WriteLine($"Removed: {removedCount}, Remaining: {string.Join(", ", numbers)}");
}
}</int></int>
运行上述代码,输出结果为 Removed: 3, Remaining: 1, 3, 5。RemoveAll 返回实际删除的元素数量,并且不需要关心索引变化,代码更简洁且不易出错。










