通过搜索键子字符串返回字典中键的存在 [英] Returning the existence of a key in a dict by searching key substring

查看:70
本文介绍了通过搜索键子字符串返回字典中键的存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串人(键)和字符串地址(值)的字典.我想拥有一个if语句,如果我的词典中的任何键包含子字符串"anders",则返回true.有什么办法吗?我已经尝试过dict.ContainsKey("anders"),但是如果任何键被显式命名为'anders',它只会返回true.我希望它即使键为Anderson或Andersen也能返回true.我知道这是一个很奇怪的情况,但我出于目的需要它.

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.

谢谢

推荐答案

字典关键字没有通配符搜索".为了进行这种类型的搜索,您将失去字典给您的O(常量)搜索.

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.

您将必须遍历字典的键,并查找包含所需子字符串的键.请注意,这将是O(n * X)迭代,其中n是键的数量,X是键字符串的平均大小.

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.

这篇关于通过搜索键子字符串返回字典中键的存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆