How to make String.Contains case insensitive?

C#.Netvb.netStringCase Insensitive

C# Problem Overview


How can I make the following case insensitive?

myString1.Contains("AbC")

C# Solutions


Solution 1 - C#

You can create your own extension method to do this:

public static bool Contains(this string source, string toCheck, StringComparison comp)
  {
    return source != null && toCheck != null && source.IndexOf(toCheck, comp) >= 0;
  }

And then call:

 mystring.Contains(myStringToCheck, StringComparison.OrdinalIgnoreCase);

Solution 2 - C#

You can use:

if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {
    //...
}

This works with any .NET version.

Solution 3 - C#

bool b = list.Contains("Hello", StringComparer.CurrentCultureIgnoreCase);

[EDIT] extension code:

public static bool Contains(this string source, string cont
                                                    , StringComparison compare)
{
    return source.IndexOf(cont, compare) >= 0;
}

This could work :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCJ7View Question on Stackoverflow
Solution 1 - C#Tobia ZambonView Answer on Stackoverflow
Solution 2 - C#joeView Answer on Stackoverflow
Solution 3 - C#Kamil BudziewskiView Answer on Stackoverflow