英文:
check if dictionary contains a Key with some masked chars and get its key value
问题
我可以使用.ContainsKey()
方法来检查字典中是否存在一个键。但是,现在我需要找出字典是否包含与某些字符匹配的键。
Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add("ABC", 1);
myDict.Add("AAA", 2);
所以我需要查找字典是否包含例如任何键为'A*C'
的情况,其中*
表示不关心。
预期结果:true。
然后,我需要获取匹配的键。
预期结果:"ABC"
。
也许可以使用 Linq 来实现这个吗?
英文:
I can check if a key is present in a dictionary using .ContainsKey() method. However, I need to find now if a dictionary contains any key that matches only some chars.
Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add("ABC", 1);
myDict.Add("AAA", 2);
So I need to find if the dictionary contains for example any key as 'A*C'
, where *
means that doesn't care.
Expected result : true.
Then, I need to get the coincidence/s key/s that matches.
Expected result : "ABC"
.
Maybe Linq is able to do this?
答案1
得分: 1
是的,你可以借助 Linq 和 正则表达式 来实现。如果键只包含字母
using System.Linq;
using System.Text.RegularExpressions;
...
string pattern = "A*C";
bool hasKey = myDict
.Keys
.Any(key => Regex.IsMatch(key, pattern.Replace('*', '.')));
这并不是一个最优的方法,因为它在 O(N) 的时间内线性搜索所有键,与通常的 O(1) 查找相比。
英文:
Yes, you can do it with a help of Linq and Regular Expressions. If keys consist of letters only
using System.Linq;
using System.Text.RegularExpressions;
...
string pattern = "A*C";
bool hasKey = myDict
.Keys
.Any(key => Regex.IsMatch(key, pattern.Replace('*', '.')));
This is not an optimal approach as it linearly searches all keys in O(N), as opposed to the usual O(1) lookup.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论