使用 list 方法并传入匹配谓词是删除指定范围内元素最高效的做法。该方法会原地遍历列表,移除所有满足条件的元素,返回被移除的数量,无需手动处理索引偏移或创建新集合。对于数值类型,只需在谓词中定义范围边界即可。

RemoveAll 如何根据条件筛选并移除元素
RemoveAll 接受一个 Predicate 委托,对列表中每个元素执行判断。如果委托返回 true,该元素即被移除。这种方法避免了在循环中调用 RemoveAt 导致的性能损耗和索引错误,因为内部实现会一次性完成元素的移动和计数更新。

using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<int> numbers = new List<int> { 1, 5, 10, 15, 20, 25, 30 };
// 删除 10 到 20 之间(包含边界)的元素
int removedCount = numbers.RemoveAll(n => n >= 10 && n <p>预期输出:<br>Removed: 3<br>1, 5, 25, 30</p>
<h2>如何处理非连续范围或复杂逻辑的删除</h2>
<p>当需要删除多个不连续区间或基于更复杂的逻辑时,可以在谓词中组合多个条件。例如,删除小于 5 或大于 25 的元素,等价于保留中间部分。这种写法依然保持单次遍历的高效性,且代码意图清晰。</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>
<p><img src="https://img.php.cn/upload/article/001/431/639/179452865598072.png?x-oss-process=image/resize,p_40" alt="C#List怎么删除数值在指定范围内的元素?"></p>
<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, 5, 10, 15, 20, 25, 30 };
// 删除不在 [5, 25] 范围内的元素
int removedCount = numbers.RemoveAll(n => n 25);
Console.WriteLine($"Removed: {removedCount}");
Console.WriteLine(string.Join(", ", numbers));
}
}</int></int>
预期输出:
Removed: 2
5, 10, 15, 20, 25
删除操作后列表容量与内存变化
RemoveAll 仅减少 Count 属性,不会自动缩小底层数组的 Capacity。这意味着内存不会立即释放,但后续添加元素时无需重新分配大块内存。如果需要回收内存,可手动调用 Capacity = Count 或在初始化时使用 TrimExcess 相关逻辑,但在大多数场景下,保持容量不变有助于提升后续插入性能。









