C # List Remove Case Insensitivity

I want to remove a word from the list. The problem is that the word to be deleted is the user, and it must be case insensitive.

I know how to make case insensitive comparisons. But that does not work.

List<string> Words = new List<string>();
Words.Add("Word");
Words.Remove("word", StringComparer.OrdinalIgnoreCase);

Is there any way to do this?

Thanks in advance

+4
source share
3 answers

To delete all

Words.RemoveAll(n => n.Equals("word", StringComparison.OrdinalIgnoreCase));

to remove the first occurrence, for example Remove:

Words.RemoveAt(Words.FindIndex(n => n.Equals("word", StringComparison.OrdinalIgnoreCase)));
+8
source

You can try using the RemoveAll () method :

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

, :

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

Source: https://habr.com/ru/post/1530831/


All Articles