Check if dictionary contains substring?

 ̄綄美尐妖づ 提交于 2019-12-01 23:24:55

问题


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?


回答1:


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

dictionary.Any(kvp=>kvp.Value.Contains("Hello"))



回答2:


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




回答3:


dictionary.Values.Any(v => v.Contains("Hello"));

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



来源:https://stackoverflow.com/questions/15445432/check-if-dictionary-contains-substring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!