You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中删除List<string>集合内以指定字母开头的字符串元素

C# 移除List中符合首字母条件元素的正确实现方式

原代码问题说明

你提供的代码运行时会抛出InvalidOperationException异常,原因是foreach遍历依赖迭代器,迭代器要求遍历过程中原集合不能发生增、删操作,否则会破坏迭代器的状态导致运行报错。
就算特殊场景下未直接报错,也会出现元素漏判问题:移除元素后后续元素的索引会自动前移,会导致紧邻被删元素的下一个元素被跳过遍历,比如你的示例中移除Australia之后,Austria会被漏判,无法正常删除。

推荐实现方式

  • 方法1:使用List自带RemoveAll方法(最简洁,性能最优)
    直接调用内置方法批量删除符合条件的元素,不需要手动写遍历逻辑:
var countries = new List<string>() { "India", "Australia", "Austria", "Canada", "Mexico", "Japan" };
// 移除所有首字母为A的元素
countries.RemoveAll(country => country.StartsWith("A"));
// 输出结果
foreach (string country in countries)
{
    Console.WriteLine(country);
}
  • 方法2:倒序for循环遍历删除(适合需要自定义复杂删除逻辑的场景)
    倒序遍历不会因为元素索引前移导致漏判:
var countries = new List<string>() { "India", "Australia", "Austria", "Canada", "Mexico", "Japan" };
for (int i = countries.Count - 1; i >= 0; i--)
{
    if (countries[i].StartsWith("A"))
    {
        countries.RemoveAt(i);
    }
}
foreach (string country in countries)
{
    Console.WriteLine(country);
}
  • 方法3:筛选生成新集合(适合不需要修改原集合对象的场景)
    筛选出不需要删除的元素生成新集合,直接替换原变量:
var countries = new List<string>() { "India", "Australia", "Austria", "Canada", "Mexico", "Japan" };
countries = countries.Where(country => !country.StartsWith("A")).ToList();
foreach (string country in countries)
{
    Console.WriteLine(country);
}

补充注意点

如果需要同时匹配大小写a开头的元素,可以给StartsWith方法增加忽略大小写参数:
country.StartsWith("A", StringComparison.OrdinalIgnoreCase)

内容的提问来源于stack exchange,提问作者Joe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 15:54:11