0

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 'anders'. Is there any way to do this? I have tried dict.ContainsKey("anders") but that just returns true if any key is explicitly named 'anders'. I would like it to return true even if the key is anderson or andersen. I know this is a pretty strange case but i need it for a purpose.

Thanks

John Baum
  • 3,183
  • 11
  • 42
  • 90

6 Answers6

6

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"))
M.Babcock
  • 18,753
  • 6
  • 54
  • 84
2

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);
Community
  • 1
  • 1
Joshua Honig
  • 12,925
  • 8
  • 53
  • 75
1
var pair = dict.FirstOrDefault(kvp => kvp.Key.Contains("anders"));
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

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.

Randolpho
  • 55,384
  • 17
  • 145
  • 179
0
if(dict.Keys.Any(k=>k.Contains("anders")))
{
    //do stuff
}
Călin Darie
  • 5,937
  • 1
  • 18
  • 13
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"));
dtb
  • 213,145
  • 36
  • 401
  • 431