【问题标题】:How to remove a string from the list, by looking at a certain letter?如何通过查看某个字母从列表中删除字符串?
【发布时间】:2022-01-04 12:13:29
【问题描述】:
var countries = new List<string>() { "India", "Australia", "Austria", "Canada", "Mexico", "Japan" };
            foreach(string country in countries)
            {
                if (country.StartsWith("A"))
                {
                    countries.Remove(country);
                }
            }
            foreach (string country in countries)
            {
                Console.WriteLine(country);
            }

例如,我想去掉以字母 A 开头的国家

【问题讨论】:

标签: c# string list letter


【解决方案1】:

我建议您使用RemoveAll() (link to documentation),它需要一个条件来知道是否必须删除元素

你可以这样做:

// The List declaration you provided
var countries = new List<string>() { "India", "Australia", "Austria", "Canada", "Mexico", "Japan" };

// Replace your first `foreach(string country in countries)` with this line
countries.RemoveAll(country => country.StartsWith("A"));

// The way of displaying data you provided
foreach (string country in countries)
{
    Console.WriteLine(country);
}

编辑:正如 Johnathan Barclay 在 cmets 中所说,“如果您想执行不区分大小写的搜索,您应该提供 StringComparison 而不是使用 ToUpper()”,就像我在未编辑的答案中所做的那样。

代码是:

// The List declaration you provided
var countries = new List<string>() { "India", "Australia", "Austria", "Canada", "Mexico", "Japan" };

// Replace your first `foreach(string country in countries)` with this line
countries.RemoveAll(country => country.StartsWith("a", StringComparison.InvariantCultureIgnoreCase));

// The way of displaying data you provided
foreach (string country in countries)
{
    Console.WriteLine(country);
}

【讨论】:

  • 你用.ToUpper()改变逻辑
  • @fubo 问题是“摆脱以字母 A 开头的国家”,所以我确保所有带有字母 A 的国家都被删除,大小写的敏感性没有请求
  • 如果要执行不区分大小写的搜索,应提供StringComparison 而不是ToUpper()
  • (尽管 List&lt;T&gt;.RemoveAll 的 MSDN 页面上的示例是这样说的)
  • 好的,我在答案中添加这部分谢谢@fubo
【解决方案2】:

是的,您可以使用RemoveAll() 属性来获得您想要的结果。

var countries = new List<string>() { "India", "Australia", "Austria"};

countries.RemoveAll(Country=>country.StartsWith("A"))

【讨论】:

  • 这已被先前的答案所涵盖,实际上已编译(您不会)
【解决方案3】:

使用RemoveAll()接近

List<string> countries = new List<string>() { "India", "Australia", "Austria", "Canada", "Mexico", "Japan" };
countries.RemoveAll(country => country.StartsWith("A"));
countries.ForEach(Console.WriteLine);

【讨论】:

  • 是的,RemoveAll 会起作用,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-23
  • 1970-01-01
  • 2020-03-20
  • 1970-01-01
  • 2019-02-12
相关资源
最近更新 更多