我想从列表中删除一个单词。问题是要删除的单词是用户输入,它应该不区分大小写。
我知道如何进行不区分大小写的比较。但这似乎不起作用。
List<string> Words = new List<string>();
Words.Add("Word");
Words.Remove("word", StringComparer.OrdinalIgnoreCase);
有办法做到这一点吗?
提前致谢
答案 0 :(得分:10)
删除所有
Words.RemoveAll(n => n.Equals("word", StringComparison.OrdinalIgnoreCase));
删除第一次出现,例如Remove
:
Words.RemoveAt(Words.FindIndex(n => n.Equals("word", StringComparison.OrdinalIgnoreCase)));
答案 1 :(得分:1)
您可以尝试使用RemoveAll()方法:
List<string> Words = new List<string>();
Words.Add("Word");
Words.RemoveAll(o => o.Equals("word", StringComparison.OrdinalIgnoreCase));
答案 2 :(得分:0)
这是一个扩展函数,它将执行相同的操作:
public static void Remove(this List<string> words, string value, StringComparison compareType, bool removeAll = true)
{
if (removeAll)
words.RemoveAll(x => x.Equals(value, compareType));
else
words.RemoveAt(words.FindIndex(x => x.Equals(value, compareType)));
}
作为额外的好处,这将删除以指定字符串开头的值:
public static void RemoveStartsWith(this List<string> words, string value, StringComparison compareType, bool removeAll = true)
{
if (removeAll)
words.RemoveAll(x => x.StartsWith(value, compareType));
else
words.RemoveAt(words.FindIndex(x => x.StartsWith(value, compareType)));
}
用法示例:
wordList.Remove("text to remove", StringComparison.OrdinalIgnoreCase);
wordList.RemoveStartsWith("text to remove", StringComparison.OrdinalIgnoreCase);