How to ignore the case sensitivity in List

前端 未结 11 751
旧时难觅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:57

    For those of you having problems with searching through a LIST of LISTS, I found a solution.

    In this example I am searching though a Jagged List and grabbing only the Lists that have the first string matching the argument.

    List<List<string>> TEMPList = new List<List<string>>();
    
    TEMPList = JaggedList.FindAll(str => str[0].ToLower().Contains(arg.ToLower()));
    
    DoSomething(TEMPList);
    
    0 讨论(0)
  • 2020-11-30 09:57

    One of possible (may not be the best), is you lowercase all of the strings put into sl. Then you lowercase the searchKeyword.

    Another solution is writing another method that lowercase 2 string parameters and compares them

    0 讨论(0)
  • 2020-11-30 09:58

    You CAN use Contains by providing the case-insensitive string equality comparer like so:

    if (myList.Contains(keyword, StringComparer.OrdinalIgnoreCase))
    {
        Console.WriteLine("Keyword Exists");
    }
    
    0 讨论(0)
  • 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));
    
    0 讨论(0)
  • 2020-11-30 10:01

    Use Linq, this adds a new method to .Compare

    using System.Linq;
    using System.Collections.Generic;
    
    List<string> MyList = new List<string>();
    MyList.Add(...)
    if (MyList.Contains(TestString, StringComparer.CurrentCultureIgnoreCase)) {
        //found
    } 
    

    so presumably

    using System.Linq;
    ...
    
    List<string> searchResults = sl.FindAll(s => s.Contains(seachKeyword, StringComparer.CurrentCultureIgnoreCase));  
    
    0 讨论(0)
  • 2020-11-30 10:01

    Simply, you can use LINQ query as like below,

    String str = "StackOverflow";
    int IsExist = Mylist.Where( a => a.item.toLower() == str.toLower()).Count()
    if(IsExist > 0)
    {
         //Found
    }
    
    0 讨论(0)
提交回复
热议问题