检查字典是否包含具有一些掩码字符的键并获取其键值。

huangapple go评论76阅读模式
英文:

check if dictionary contains a Key with some masked chars and get its key value

问题

我可以使用.ContainsKey()方法来检查字典中是否存在一个键。但是,现在我需要找出字典是否包含与某些字符匹配的键。

  1. Dictionary<string, int> myDict = new Dictionary<string, int>();
  2. myDict.Add("ABC", 1);
  3. 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.

  1. Dictionary&lt;string, int&gt; myDict = new Dictionary&lt;string, int&gt;();
  2. myDict.Add(&quot;ABC&quot;, 1);
  3. myDict.Add(&quot;AAA&quot;, 2);

So I need to find if the dictionary contains for example any key as &#39;A*C&#39;, where * means that doesn't care.

Expected result : true.

Then, I need to get the coincidence/s key/s that matches.

Expected result : &quot;ABC&quot;.
Maybe Linq is able to do this?

答案1

得分: 1

是的,你可以借助 Linq正则表达式 来实现。如果键只包含字母

  1. using System.Linq;
  2. using System.Text.RegularExpressions;
  3. ...
  4. string pattern = "A*C";
  5. bool hasKey = myDict
  6. .Keys
  7. .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

  1. using System.Linq;
  2. using System.Text.RegularExpressions;
  3. ...
  4. string pattern = &quot;A*C&quot;;
  5. bool hasKey = myDict
  6. .Keys
  7. .Any(key =&gt; Regex.IsMatch(key, pattern.Replace(&#39;*&#39;, &#39;.&#39;)));

This is not an optimal approach as it linearly searches all keys in O(N), as opposed to the usual O(1) lookup.

huangapple
  • 本文由 发表于 2023年6月19日 03:55:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76502313.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定