當然,創建一個詞典,其中包含一側的值列表和另一側的響應。
private IDictionary<List<String>, List<String>> _responses = new Dictionary<List<String>, List<String>>();
_responses.Add(
new List<String> { "Hello there!", "Hey mate", "Hi!" }},
new List<String> { "sup");
_responses.Add(
new List<String> { "Buddy", "Mate", "Hombre" }},
new List<String> { "sup");
現在爲了找回的東西:
foreach(var keyword in _responses.Keys){
if(keywords.Contains("sup"){
return _responses[keyword];
}
}
搜索 「SUP」 將返回的適當的應對措施清單。我也使用List<String>
作爲查找值,以便您可以將多個關鍵字鏈接到相同的搜索結果。
,如果你要進入由多個值的字符串,只需添加外環它:
整個重寫:
這個例子假設你有一個輸入字符串。您的要求是檢查此輸入字符串是否包含任何一組字詞。應該能夠通過一個單詞來引用每組單詞。
void Main()
{
var babel = new Babel("hi homies, this is for my mate out there.");
if(babel.HasAnswer("sup") && babel.HasAnswer("friend")){
Console.WriteLine ("It has both!");
} else {
Console.WriteLine ("Boo Jeroen you suck");
}
}
public class Babel {
private IDictionary<List<String>, List<String>> _responses = new Dictionary<List<String>, List<String>>();
private String query;
public Babel(string query){
this.query = query;
_responses.Add(
new List<String> { "sup" },
new List<String> { "hello", "hey", "hi"});
_responses.Add(
new List<String> {"friend" },
new List<String> { "buddy", "mate", "hombre" });
}
public bool HasAnswer(string input){
foreach(var token in input.Split(' ')) {
foreach(var keyword in _responses.Keys){
if(keyword.Contains(token)){
return ContainsAny(_responses[keyword]);
}
}
}
return false;
}
private bool ContainsAny(List<String> toCompare){
foreach(string item in toCompare){
foreach(string token in query.Split(' ')){
if(token == item) return true;
}
}
return false;
}
}
輸出:
它既有!
這種方法的好處是:添加一組新單詞就像向詞典添加條目一樣簡單。非常高的可擴展性!你也可以讓多個值引用同一個列表(如果你想創建應該引用與「sup」相同的值的「howdie」,你可以將它添加到列表中並且完成)。
如果你使用'if',讓我先向任何正在處理你的代碼的人表示我的哀悼。 –