gpt4 book ai didi

c# - 字典通配符搜索

转载 作者:行者123 更新时间:2023-11-30 14:33:33 25 4
gpt4 key购买 nike

我正在尝试使用通配符和 Dictionary 类创建字符串搜索

Dictionary<string, Node> Nodes = new Dictionary<string, Node>();

public bool ResponceSearch(string search) {
if (Nodes.ContainsKey(search)) {
label1.Text = Nodes[search].GetResult();
return true;
}
}

搜索字符串如

What is that

并且字典包含键,例如

Who is *
What is *

因此搜索会根据“what is that”搜索字符串找到“what is *”。

最佳答案

如果你能改变你的字典键是正确的regular expressions ,比如:

@"Who is \w+"
@"What is \w+"

那么这个问题就变得简单了很多:

public bool ResponceSearch(string search) {
var node =
(from p in Nodes
where Regex.Matches(p.Key, search)
select p.Value)
.FirstOrDefault();
if (node != null) {
label1.Text = node.GetResult();
return true;
}
}

您甚至可以为此编写扩展方法。例如:

public static bool ContainsKeyPattern<T>(this Dictionary<string, T> nodes, string search) 
{
return nodes.Keys.Any(k => Regex.Matches(k, search));
}

public static T GetItemByKeyPattern<T>(this Dictionary<string, T> dict, string search)
{
return
(from p in dict
where Regex.Matches(p.Key, search)
select p.Value)
.First();
}

关于c# - 字典通配符搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16070436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com