list一次调用只会删除第一个匹配的元素。该方法从列表头部开始遍历,找到第一个与指定对象相等的项后立即移除并返回true,后续相同的元素不受影响。

Remove方法在内部是如何定位并移除元素的?
Remove方法通过Equals比较查找元素,找到后使用Array.Copy将后续元素向前移动一位以填补空缺,最后将末尾多余位置置为默认值。这个过程是线性的,时间复杂度为O(n)。

using System;
using System.Collections.Generic;
class Program {
static void Main() {
var list = new List<int> { 1, 2, 2, 3 };
bool result = list.Remove(2);
Console.WriteLine($"Removed: {result}");
Console.WriteLine(string.Join(", ", list));
}
}</int>
如果我想一次性删除列表中所有相同的元素该怎么办?
如果需要删除所有匹配项,应使用RemoveAll方法或手动倒序遍历并使用RemoveAt。RemoveAll接受一个谓词委托,会移除所有满足条件的元素并返回移除的数量。
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var list = new List<int> { 1, 2, 2, 3, 2 };
int count = list.RemoveAll(x => x == 2);
Console.WriteLine($"Removed count: {count}");
Console.WriteLine(string.Join(", ", list));
}
}</int>










