How to ignore upper and lower case in the Contains method?

Asked

Viewed 323 times

0

I have two List with some strings, for example:

List<string> lista1 = new List<string>();
lista.Add("string1");
lista.Add("string2");
lista.Add("STRING3");

List<string> lista2 = new List<string>();
lista.Add("STRING1");
lista.Add("STRING2");
lista.Add("string3");
lista.Add("STRING4");

I need to delete from Lista2, all strings that exist in list1, ignoring whether the letter is uppercase or lowercase.

I have that code:

for (int i = lista2.Count - 1; i >= 0; i--)
{
    if (lista1.Contains(lista2[i]))
        listMensagem.RemoveAt(i);
}

But that doesn’t ignore the upper and lower case letters. I tried to use the StringComparison.OrdinalIgnoreCase but the method Contains unaccepted.

In this example I gave, Lista2 would have to keep only the STRING4 how can I do this?

  • 1

    has no way with contains, you can match the two strings with toupper or tolower, or you can exchange the contains for an index

1 answer

2


Use the method RemoveAll with an expression for comparison:

lista2.RemoveAll(item1 => lista1.Any(item2 => item2.Equals(item1, StringComparison.OrdinalIgnoreCase)));

Don’t forget to include the namespace System.Linq.

  • 1

    I put it on the fiddle for easy viewing: https://dotnetfiddle.net/qtBns9

Browser other questions tagged

You are not signed in. Login or sign up in order to post.