How to make String.Contains case insensitive?

This question already has an answer here:

  • Case insensitive 'Contains(string)' 22 answers

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

    You can use:

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

    This works with any .NET version.


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

    链接地址: http://www.djcxy.com/p/13080.html

    上一篇: 在案例中查找一个子字符串

    下一篇: 如何使String.Contains不区分大小写?