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
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);
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"));
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.
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"))
var pair = dict.FirstOrDefault(kvp => kvp.Key.Contains("anders"));
if(dict.Keys.Any(k=>k.Contains("anders")))
{
//do stuff
}