Reputation: 447
I want to remove a word from a List. The problem is that the word to delete is user input, and it should be case insensitive.
I know how to do case insensitive comparisons. But this doesn't seem to work.
List<string> Words = new List<string>();
Words.Add("Word");
Words.Remove("word", StringComparer.OrdinalIgnoreCase);
Is there a way to do this?
Thanks in advance
Upvotes: 7
Views: 9665
Reputation: 867
Here is an extension function that will do the same thing:
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)));
}
As an added bonus, this removes values that start with a specified string:
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)));
}
Usage example:
wordList.Remove("text to remove", StringComparison.OrdinalIgnoreCase);
wordList.RemoveStartsWith("text to remove", StringComparison.OrdinalIgnoreCase);
Upvotes: 1
Reputation: 33364
To remove all
Words.RemoveAll(n => n.Equals("word", StringComparison.OrdinalIgnoreCase));
to remove first occurrence, like Remove
:
Words.RemoveAt(Words.FindIndex(n => n.Equals("word", StringComparison.OrdinalIgnoreCase)));
Upvotes: 22
Reputation: 89285
You can try to use RemoveAll() method :
List<string> Words = new List<string>();
Words.Add("Word");
Words.RemoveAll(o => o.Equals("word", StringComparison.OrdinalIgnoreCase));
Upvotes: 2