6

Say I have two dictionaries with the following key value pairs:

1, "Hello"
2, "Example"

And another dictionary as follows:

1, "HelloWorld"
2, "Example2"

I want to find out if these dictionaries contain the substring "hello" within them.
dictionary.ContainsValue("Hello") will work for the first example but not the second one. How can I check for existence of a substring in all values in a dictionary?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
john cs
  • 2,220
  • 5
  • 32
  • 50

3 Answers3

15

Just use Any to to check for the first Value that contains "Hello"

dictionary.Any(kvp=>kvp.Value.Contains("Hello"))
juharr
  • 31,741
  • 4
  • 58
  • 93
1

Dictionary doesn't allow to search for substrings. To find it, you need to enumerate all values and check each for substring, as suggested by juharr. However, this method is highly inefficient. Use it only if you don't care about search performance at all.
If you need good performance, use suffix array algorithm. https://en.wikipedia.org/wiki/Suffix_array

user626528
  • 13,999
  • 30
  • 78
  • 146
  • This seems like overkill and wouldn't work for finding "Hello" in "HelloWorld" because "Hello" isn't a suffix in that case. – juharr Mar 16 '13 at 04:30
  • @juharr, this might be overkill if TS doesn't care about performance, but you obviously don't understand what is suffix array algorithm. It always finds _any_ substrings. – user626528 Mar 16 '13 at 04:33
  • Clearly you should explain what suffix array algorithm is and how it works. – scenia Aug 05 '15 at 10:52
  • @scenia, the referenced Wikipedia article contains all information about suffix array you need. – user626528 Dec 08 '16 at 07:15
0
dictionary.Values.Any(v => v.Contains("Hello"));

Dictionary isn't an IEnumerable itself so it won't have LINQ extensions apply to it.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Kevin
  • 429
  • 3
  • 10