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

前端 未结 6 734
借酒劲吻你
借酒劲吻你 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);
    
    0 讨论(0)
  • 2020-12-20 09:49

    You can iterate the keys of the dictionary and check each if it contains the string:

    bool found = false;
    foreach (string key in dict.Keys)
    {
        if (key.Contains("anders"))
        {
            found = true;
            break;
        }
    }
    

    or using LINQ:

    bool found = dict.Keys.Any(key => key.Contains("anders"));
    
    0 讨论(0)
  • 2020-12-20 09:55

    There is no "wildcard search" for dictionary keys. In order to do this type of search, you are going to lose the O(constant) search that a dictionary gives you.

    You'll have to iterate over the keys of the dictionary and look for those that contain the substring you require. Note that this will be an O(n*X) iteration, where n is the number of keys and X is the average size of your key string.

    There's a nifty one-liner that will help:

    bool containsKey = myDictionary.Keys.Any(x => x.Contains("mySubString"));
    

    But it's a heavy operation.

    0 讨论(0)
  • 2020-12-20 09:59

    You'll have to iterate over the collection and check each one. The LINQ Any method makes this fairly simple:

    dict.Keys.Any(k => k.Contains("anders"))
    
    0 讨论(0)
  • 2020-12-20 10:00
    var pair = dict.FirstOrDefault(kvp => kvp.Key.Contains("anders"));
    
    0 讨论(0)
  • 2020-12-20 10:04
    if(dict.Keys.Any(k=>k.Contains("anders")))
    {
        //do stuff
    }
    
    0 讨论(0)
提交回复
热议问题