Question

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

Was it helpful?

Solution

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)));

OTHER TIPS

You can try to use RemoveAll() method :

List<string> Words = new List<string>();
Words.Add("Word");
Words.RemoveAll(o => o.Equals("word", StringComparison.OrdinalIgnoreCase));

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top