在c#中删除list中多个指定位置的元素,最稳妥的做法是将需要删除的索引按从大到小(倒序)排序后依次调用 removeat。因为 list 会移除该位置元素并将后续元素前移,导致原索引失效;若正序删除,后面的索引会因前面的移除而错位,引发 argumentoutofrangeexception 或删错数据。倒序删除则保证每次操作时,尚未处理的较小索引不受影响。

为什么正序删除会导致索引错位?
正序删除时,每移除一个元素,其后的所有元素索引减一。例如原列表有5个元素,要删除索引0和1。先删0,原索引1的元素移到新索引0,此时再删“原索引1”实际删的是新索引0之后的那个元素,导致逻辑错误。因此必须避免正序直接遍历删除。

using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
var list = new List<int> { 10, 20, 30, 40, 50 };
// 待删除的原始索引:1 和 3
var indicesToRemove = new List<int> { 1, 3 };
// 关键步骤:倒序排序
indicesToRemove.Sort((a, b) => b.CompareTo(a));
foreach (var idx in indicesToRemove)
{
if (idx <p>预期输出:<code>10, 30, 50</code>。先删索引3(值40),列表变为 <code>{10, 20, 30, 50}</code>;再删索引1(值20),列表变为 <code>{10, 30, 50}</code>。结果正确。</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>
<h2>如何验证倒序删除的正确性?</h2>
<p>通过对比删除前后的元素值与预期集合,可验证逻辑。上述代码中,输入为 <code>{10, 20, 30, 40, 50}</code>,目标删除索引1和3。倒序处理后,剩余元素应为 <code>{10, 30, 50}</code>,与输出一致。若改为正序删除,将得到错误结果或异常。</p>
<p><img src="https://img.php.cn/upload/article/001/431/639/179651671765715.png?x-oss-process=image/resize,p_40" alt="C#怎么删除List中多个指定位置的元素?倒序删除示例"></p>
<h2>如果索引超出范围怎么办?</h2>
<p>在删除前需检查索引是否有效。示例中已加入 <code>if (idx 判断,防止 <code>ArgumentOutOfRangeException</code>。也可使用 <code>list.RemoveWhere</code> 配合条件过滤,但仅适用于基于值的删除,而非基于原始索引的多点删除。对于固定索引列表,倒序 <code>RemoveAt</code> 是最直接且安全的方式。</code></p></int></int>









