3

钩词是一个词,您可以在开头或结尾添加一个字母并组成一个新词。

我有一个相当大的单词列表(大约 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);

当我尝试从中访问任何东西时,hookBase它会旋转几分钟,然后我放弃并杀死它。

任何人都可以看到我尝试这样做的任何明显错误吗?有关更有效方式的任何建议?

4

2 回答 2

6

首先, 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); }
}

如果您想使用 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();

在线查看它:ideone

于 2012-05-10T06:48:54.813 回答
-1

我最近做了类似的事情。我尝试使用 linq,在 ddbb 和存储过程中存储带有正则表达式的 .net 程序集。我发现最有效的方法是使用存储过程。微软针对此类操作对事务引擎进行了高度优化。

最好的祝福

于 2012-05-10T07:01:51.310 回答