Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#字典在使用containsValue()时运行缓慢_C#_Dictionary_Foreach - Fatal编程技术网

C#字典在使用containsValue()时运行缓慢

C#字典在使用containsValue()时运行缓慢,c#,dictionary,foreach,C#,Dictionary,Foreach,我有一个HashSet,其中包含从读取二进制文件生成的自定义对象。我还有一个通过读取DBF文件的每一行生成的字典。这两个列上都有一个索引属性。例如,字典中的第10项将与哈希集中的第10项对齐 我正在比较大量的数据。可以有10000到500000条记录。应用程序检查其他两个文件(一个二进制文件,另一个是dbf)是否存在差异。它检查对象的哈希代码(由某些属性生成,它可以快速轻松地进行比较) 下面是我如何构建每个单独的字典(mod也有一个类似的字典): 我的尝试/其他想法 -生成自定义对象的哈希集,自

我有一个HashSet,其中包含从读取二进制文件生成的自定义对象。我还有一个通过读取DBF文件的每一行生成的字典。这两个列上都有一个索引属性。例如,字典中的第10项将与哈希集中的第10项对齐

我正在比较大量的数据。可以有10000到500000条记录。应用程序检查其他两个文件(一个二进制文件,另一个是dbf)是否存在差异。它检查对象的哈希代码(由某些属性生成,它可以快速轻松地进行比较)

下面是我如何构建每个单独的字典(mod也有一个类似的字典):

我的尝试/其他想法

-生成自定义对象的哈希集,自定义对象的索引为整数,字符串为列和值的长度

-删除if(!(modDRdict.ContainsValue(origDRdict[i]))块可以显著加快代码速度。在两个440000记录文件之间迭代删除的记录只需一分钟查字典要花很长时间


-我认为foreach循环中的foreach循环不会造成太多开销。如果我将它保留在代码中,但不进行查找,那么它仍然运行得很快。

字典优化为按键而不是按值查找。如果需要按值查找,则使用了错误的词典。你需要在你的值上建立一个哈希集来快速检查是否包含,或者如果你需要键的话建立一个反向字典。

当你执行ContainsKey not ContainsValue…时,字典很有用(即快速)。要展开,
ContainsKey
是o(1),而
ContainsValue
是o(n)。而不是Contains,您可以使用TryGetValue。它大约快了40%,正如您在本文中看到的,所以使用ContainsKey应该会显著提高速度?我将尝试这个和TryGetValue。字典和散列集是无序的,所以谈论它们中的第10个元素没有任何意义。
foreach (DataRow row in origDbfFile.datatable.Rows)
{
    string str = "";
    foreach (String columnName in columnNames)
    {
        str += "~" + row.Field<Object>(columnName);
    }
    origDRdict.Add(d, str);
    d++;
}
foreach (CustomClass customclass in origCustomClassList) {
    Boolean foundIt = false;
    if (modCustomClassList.Contains(customclass))
    {
        foundIt = true;
    }
    //at this point, an element has not been found
    if (!foundIt)
    {
        notFoundRecords.Add(customclass);

    } 
    //If I remove this entire else block, code runs fast.
    else //at this point an element has been found
    {
        //
        //check 'modified' dictionary array
        if (!(modDRdict.ContainsValue(origDRdict[i])))
        {
            //at this point, the coordinates are the same, 
            //however there are DB changes
            //this is where I would do a full check based on indexes 
            //to show changes. 
        }
    }

    i++; //since hashsets can't be indexed, we need to increment
}