How to ignore the case sensitivity in List

前端 未结 11 752
旧时难觅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 10:04
    StringComparer.CurrentCultureIgnoreCase is a better approach instead of using indexOf.
    
    0 讨论(0)
  • 2020-11-30 10:06

    The FindAll does enumeration of the entire list.

    the better approach would be to break after finding the first instance.

    bool found = list.FirstOrDefault(x=>String.Equals(x, searchKeyWord, Stringcomparison.OrdinalIgnoreCase) != null;

    0 讨论(0)
  • 2020-11-30 10:08

    You can apply little trick over this.
    Change all the string to same case: either upper or lower case

    List searchResults = sl.FindAll(s => s.ToUpper().Contains(seachKeyword.ToUpper()));

    0 讨论(0)
  • 2020-11-30 10:11

    The optimal solution will be to ignore the case when performing the comparison

    List<string> searchResults = sl.FindAll(s => s.IndexOf(seachKeyword, System.StringComparison.OrdinalIgnoreCase) >= 0);
    
    0 讨论(0)
  • 2020-11-30 10:19

    Below method will search your needed keyword and insert all searched items into a new list and then returns new list.

    private List<string> serchForElement(string searchText, list<string> ListOfitems)
    {            
        searchText = searchText.ToLower();
        List<string> Newlist = (from items in ListOfitems
                             where items.ToLower().Contains(searchText.ToLower())
                             select items).ToList<string>(); 
    

    return Newlist; }

    0 讨论(0)
提交回复
热议问题