C# 从字符串列表中返回潜在字符串及其下一个字符性能
这是一个关于从字符串数组高效返回字符串和字符的问题,其中:C# 从字符串列表中返回潜在字符串及其下一个字符性能,c#,.net,string,performance,algorithm,C#,.net,String,Performance,Algorithm,这是一个关于从字符串数组高效返回字符串和字符的问题,其中: 字符串数组中的字符串以提供的用户输入开始 作为字符集合的这些字符串的下一个字母 其思想是,当用户键入一封信时,潜在的响应将与下一封信一起显示。因此,响应时间很重要,因此需要一个性能良好的算法 例如,如果字符串数组包含: string[] stringArray = new string[] { "Moose", "Mouse", "Moorhen", "Leopard", "Aardvark" }; 如果用户输入“Mo”,则应返回“M
string[] stringArray = new string[] { "Moose", "Mouse", "Moorhen", "Leopard", "Aardvark" };
如果用户输入“Mo”,则应返回“Moose”、“Mouse”和“Moorhen”,并为下一个字母返回字符“o”和“u”
这感觉像是LINQ的工作,因此我当前作为静态方法的实现是(我将输出存储到一个建议对象,该对象仅具有2个返回列表的属性):
公共静态建议
获取建议
(字符串用户输入,
字符串[]字符串数组)
{
//根据用户输入获取所有可能的字符串。这将始终包含
//与用户输入长度相同或更长的值。
IEnumerable possibleStrings=stringArray.Where(x=>x.StartsWith(userInput));
IEnumerable nextLetterChars=null;
//如果我们有可能的字符串,并且有一些输入,则获取下一个字母
如果(可能的限制条件)&&
!string.IsNullOrEmpty(userInput))
{
//用户输入包含字符,因此让我们查找可能的下一个字母。
nextLetterChars=
可能的限制。选择
(x=>
{
//输入与可能的字符串相同,因此返回空字符。
if(x==userInput)
{
返回“\0”;
}
其他的
{
//从可能字符串的开头删除用户输入,然后获取
//下一个角色。
返回x.Substring(userInput.Length,x.Length-userInput.Length)[0];
}
});
}//如果结束,则结束
我实现了第二个版本,它实际上将所有键入组合存储到一个字典列表中;每个单词一个,组合键和值根据实际需要而定,例如:
- 词典1:
- 键值
- M“驼鹿”
- “莫”驼鹿
- 词典2:
- 键值
- “M”“鼠标”
- “MO”“鼠标”
List<Dictionary<string, string>> animalCombinations = new List<Dictionary<string, string>>();
foreach (string animal in stringArray)
{
Dictionary<string, string> animalCombination = new Dictionary<string, string>();
string accumulatedAnimalString = string.Empty;
foreach (char character in animal)
{
accumulatedAnimalString += character;
animalCombination[accumulatedAnimalString] = animal;
}
animalCombinations.Add(animalCombination);
}
List animalcombinions=new List();
foreach(字符串数组中的字符串动物)
{
Dictionary AnimalComposition=新字典();
字符串累计animalString=string.Empty;
foreach(动物中的字符)
{
累计animalString+=字符;
动物组合[累积的动物串]=动物;
}
添加(animalcombinion);
}
然后在运行时获取可能的字符串:
// Select value entries from the list of dictionaries which contain
// keys which match the user input and flatten into one list.
IEnumerable<string> possibleStrings =
animalCombinations.SelectMany
(animalCombination =>
{
return animalCombination.Values.Where(x =>
animalCombination.ContainsKey(userInput));
});
//从包含
//与用户输入匹配并展开为一个列表的键。
i可数可能限制=
动物组合
(动物组合=>
{
返回animalcombinion.Values.Where(x=>
animalcombinion.ContainsKey(userInput));
});
因此,问题是:
如果写得正确,它们只会给同一代码的命令式版本增加很少的开销。因为它们更易于阅读、维护和编写,所以它们通常是最好的选择。看到了吗?你指的是我的评论吗?这不是批评,我想这会有帮助。否决票也不是我的。不,不是你的评论-我找到你了urs和Jason的回答真的很有帮助!你是指我的评论吗?这不是批评,我认为这会有帮助。否决票也不是我的。不,不是你的评论-我发现你和Jason的回答真的很有帮助!
// Select value entries from the list of dictionaries which contain
// keys which match the user input and flatten into one list.
IEnumerable<string> possibleStrings =
animalCombinations.SelectMany
(animalCombination =>
{
return animalCombination.Values.Where(x =>
animalCombination.ContainsKey(userInput));
});