Abe*_*ler 3 .net c# linq performance
钩子词是一个单词,您可以在开头或结尾添加一个字母并创建一个新单词.
我有一个相当大的单词列表(大约170k),我想选择5个随机钩字.问题是我使用的方法非常慢.见下文:
Random rnd = new Random();
var hookBases = (from aw in allWords //allWords is a List<string>
from aw2 in allWords
where aw2.Contains(aw)
&& aw2.Length == aw.Length + 1
&& aw[0] == 'c'
select aw).OrderBy(t => rnd.Next()).Take(5);
Run Code Online (Sandbox Code Playgroud)
当我尝试从hookBase它中获取任何东西时,我会放弃几分钟然后放弃并杀死它.
任何人都可以看到我试图这样做的任何明显错误?有关更有效方式的任何建议吗?
首先,allWords应该是a HashSet<string>而不是a List<string>,以便有效查找.
一旦完成,迭代哈希集,并检查删除第一个或最后一个字母是否给出了一个新的有效单词.那是你的勾手词.
HashSet<string> result = new HashSet<string>();
foreach (string word in allWords) {
string candidate = word.Substring(0, word.Length - 1);
if (allWords.Contains(candidate)) { result.Add(candidate); }
candidate = word.Substring(1, word.Length - 1);
if (allWords.Contains(candidate)) { result.Add(candidate); }
}
Run Code Online (Sandbox Code Playgroud)
如果你想用LINQ做这个:
List<string> hookWords = allWords
.Select(word => word.Substring(0, word.Length - 1))
.Concat(allWords.Select(word => word.Substring(1, word.Length - 1)))
.Distinct()
.Where(candidate => allWords.Contains(candidate))
.ToList();
Run Code Online (Sandbox Code Playgroud)
看到它在线工作:ideone
| 归档时间: |
|
| 查看次数: |
192 次 |
| 最近记录: |