Returning the existence of a key in a dict by searching key substring

前端 未结 6 733
借酒劲吻你
借酒劲吻你 2020-12-20 09:08

I have a dictionary of string people (key) and string addresses (value). I want to have an if statement that returns true if any key in my dictionary contains the substring

6条回答
  •  囚心锁ツ
    2020-12-20 09:49

    Everyone has already pointed out the obvious (and correct) Any method, but one note: Using String.Contains as the predicate will only return true if the case of the substring is also correct. To do a case-insensitive search, use a simple Regex:

    dict.Keys.Any(x => Regex.IsMatch(x, "(?i)anders"));
    

    Or use IndexOf with the StringComparison argument (as in Case insensitive 'Contains(string)'):

    dict.Keys.Any(x => x.IndexOf("anders", StringComparison.InvariantCultureIgnoreCase) >= 0);
    

提交回复
热议问题