How to ignore the case sensitivity in List

前端 未结 11 903
旧时难觅i
旧时难觅i 2020-11-30 09:46

Let us say I have this code

string seachKeyword = \"\";
List sl = new List();
sl.Add(\"store\");
sl.Add(\"State\");
sl.Add(\"STAM         


        
11条回答
  •  暖寄归人
    2020-11-30 09:59

    The best option would be using the ordinal case-insensitive comparison, however the Contains method does not support it.

    You can use the following to do this:

    sl.FindAll(s => s.IndexOf(searchKeyword, StringComparison.OrdinalIgnoreCase) >= 0);
    

    It would be better to wrap this in an extension method, such as:

    public static bool Contains(this string target, string value, StringComparison comparison)
    {
        return target.IndexOf(value, comparison) >= 0;
    }
    

    So you could use:

    sl.FindAll(s => s.Contains(searchKeyword, StringComparison.OrdinalIgnoreCase));
    

提交回复
热议问题