gpt4 book ai didi

c# - 使用 foreach 和 .contains 比较两个字典以查找唯一和非唯一数据的最快方法

转载 作者:太空狗 更新时间:2023-10-30 00:30:16 26 4
gpt4 key购买 nike

我目前有 2 个字典,有 30,000 个键。

我目前正在使用两个 foreach 循环来查找 dict1 中的唯一键。然后我将 dict2 中的唯一键写入另一个字典(3)。

如果键匹配,我会检查值是否相同。如果它们不相同,则打印。

是不是用foreach比较好,好像影响性能。还有其他更快的解决方案或内置功能吗? Ir shd 我试试 dict.contains 方法。


Dict1                    Dict2

Keys Values Keys Values
S0111 00000 S0000 00010
S0000 00010 S0020 00015
S0020 00015 S0040 00150
S0040 00200 S0050 00250

        foreach (KeyValuePair<string, string> sourceRow in sourceData)
{
foreach (KeyValuePair<string, string> dumpRow in dumpData)
{
// A in C, skip
if (sourceRow.Key == dumpRow.Key)
{
Is_Unique_Address = false;

if (sourceRow.Value != dumpRow.Value)
{
Data_Mismatch_Criteria(sourceRow.Key, sourceRow.Value, dumpRow.Key, dumpRow.Value);
}

}
}
}

最佳答案

此代码使您能够从 dict2 中选择键,这些键不包含在 dict1 中。

var dict1 = new Dictionary<string, string>();
var dict2 = new Dictionary<string, string>();

// Add data to both dictionaries

var uniqueKeys = dict2.Keys.Except(dict1.Keys);

这是你需要的吗?

编辑:请注意,上面的代码选择了 dict2 中不包含在 dict1 中的所有键。如果您需要检查两个词典是否具有不同的键集(并且我假设它可能是这种情况),那么您可以使用:

var areTheSame = dict2.Keys.Any(x => !dict1.ContainsKey(x))
|| dict1.Keys.Any(x => !dict2.ContainsKey(x));

编辑 2:OP 编辑​​后,我现在知道您需要什么:

var differentValues = dict2.Where(pair => dict1.ContainsKey(pair.Key))
.Select(pair => new
{
ValueA = pair.Value,
ValueB = dict1[pair.Key],
Key = pair.Key
})
.Where(x => x.ValueA != x.ValueB)
.ToList();

foreach (var differentValue in differentValues)
{
Console.WriteLine(differentValue);
}

关于c# - 使用 foreach 和 .contains 比较两个字典以查找唯一和非唯一数据的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39529611/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com