在c#中删除list首项前,必须通过检查 count 属性是否大于0来避免索引越界。直接调用 removeat(0) 会在空列表时抛出 argumentoutofrangeexception,因此只需在操作前添加一个 if (list.count > 0) 判断即可安全移除元素。

List<t></t> 在空集合时删除会抛什么异常
当 List<t></t> 为空时,直接执行 RemoveAt(0) 会立即抛出 System.ArgumentOutOfRangeException。该异常表明提供的索引不在有效范围内,因为此时列表长度为0,不存在索引为0的元素。这是C#标准库对非法访问的严格保护机制,程序若未捕获此异常将直接终止运行。

using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var list = new List<int>();
try
{
list.RemoveAt(0);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine(ex.GetType().Name);
}
}
}预期输出:
ArgumentOutOfRangeException
如何安全地移除 List 的第一个元素
安全移除首项的标准做法是结合 Count 属性进行条件判断。只有当列表非空时才执行 RemoveAt(0) 或 RemoveRange(0, 1)。这种方法逻辑清晰且性能开销极小,避免了不必要的异常处理成本。

using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var list = new List<int> { 10, 20, 30 };
if (list.Count > 0)
{
list.RemoveAt(0);
}
Console.WriteLine(list.Count); // 输出 2
}
}预期输出:
2
使用 RemoveAt(0) 对大列表的性能影响是什么
虽然 if (list.Count > 0) 能解决越界问题,但 RemoveAt(0) 的时间复杂度为 O(n),因为它需要将所有后续元素向前移动一位。对于包含大量元素的大列表,频繁删除首项会导致显著的性能下降。若业务场景允许,建议使用 Queue<t></t> 数据结构,其 Dequeue() 操作时间复杂度为 O(1)。


















