在 C# 中的字典上加速 Foreach

Speed up Foreach on Dictionary in C#

我有以下代码。字典“_ItemsDict”包含数百万条记录。此代码花费大量时间将项目添加到 associatedItemslst LIST。有没有办法加快这个过程。

foreach (var obj in lst)
{
    foreach (var item in _ItemsDict.Where(ikey => ikey.Key.StartsWith(obj))
                                   .Select(ikey => ikey.Value))
    {

        aI = new AssociatedItem
        {
            associatedItemCode = artikel.ItemCode
        };
        associatedItemslst.Add(aI);
    }
}

我不认为使用字典可以帮助您使这段代码更流畅,原因是字典适合匹配完整键而不是部分键,在您的情况下,它实际上遍历字典中的每个键并找到结果。我建议您使用其他一些数据结构来更快地获得结果,其中之一是 TRIE data structure. I have posted a blog here for auto complete using TRIE https://devesh4blog.wordpress.com/2013/11/16/real-time-auto-complete-using-trie-in-c/

而不是使用 Dictionary<TKey, TValue> 你可能想要实现 Trie/Radix Tree/Prefix Tree.

引自维基百科:

A common application of a trie is storing a predictive text or autocomplete dictionary, such as found on a mobile telephone.

(snip)

Tries are also well suited for implementing approximate matching algorithms,[6] including those used in spell checking and hyphenation[2] software.

您可以使用 Parallel.Foreach()

将时间除以因子 5 或 6
String obj = "42";
Parallel.ForEach(_ItemsDict, new ParallelOptions{ MaxDegreeOfParallelism = Environment.ProcessorCount},
            (i) =>
        {
            if (i.Key.StartsWith(obj))
                bag.Add(new AssociatedItem() { associatedItemCode = i.Value });
        });

但似乎肯定存在架构问题。 Trie 是一种方法。或者您可以使用

Dictionary<String,List<TValue>> 

在其中存储每个字符串的每个部分的所有出现,然后引用关联的对象。

最后但同样重要的是,如果您的数据来自数据库,SQL 服务器在搜索 varchar 的一部分时非常有效,子句如下:

WHERE ValueColumn like '42%' (equivalent of StartsWith("42") )