我想比较c#中的两个字典,以便得到"True"one_answers"False"的输出
var dict3 = Dict.Where(entry => Dict_BM[entry.Key] != entry.Value)
.ToDictionary(entry => entry.Key, entry => entry.Value);
我有两个不同的词典名称"Dict"one_answers"Dict_BM",我想比较一下这两个词典。请建议获得"True"one_answers"False"输出的最佳方式谢谢
我认为这是比较两个字典并返回true或false结果的最简单方法。
这个逻辑对我来说是有效的
Dictionary<string, int> Dictionary1 = new Dictionary<string, int>();
d1.Add("data1",10);
d1.Add("data2",11);
d1.Add("data3",12);
Dictionary<string, int> Dictionary2 = new Dictionary<string, int>();
d2.Add("data3", 12);
d2.Add("data1",10);
d2.Add("data2",11);
bool equal = false;
if (Dictionary1.Count == Dictionary2.Count) // Require equal count.
{
equal = true;
foreach (var pair in Dictionary1)
{
int tempValue;
if (Dictionary2.TryGetValue(pair.Key, out tempValue))
{
// Require value be equal.
if (tempValue != pair.Value)
{
equal = false;
break;
}
}
else
{
// Require key be present.
equal = false;
break;
}
}
}
if (equal == true)
{
Console.WriteLine("Content Matched");
}
else
{
Console.WriteLine("Content Doesn't Matched");
}
希望这对你有帮助。
如果您想构建一个新的字典,其中每个键的值都是一个布尔值,指示两个源字典中的条目是否相等,请尝试以下操作:
var dict3 = Dict.ToDictionary(
entry => entry.Key,
entry => Dict_BM[entry.Key] == entry.Value);
如果这两个源字典可能不包含相同的密钥,您可能想尝试这样的方法:
var dict3 = Dict.Keys.Union(Dict_BM.Keys).ToDictionary(
key => key,
key => Dict.ContainsKey(key) &&
Dict_BM.ContainsKey(key) &&
Dict[key] == Dict_BM[key]);
然而,如果您只想测试这两个字典是否包含完全相同的元素,那么您可以简单地使用以下内容:
var areEqual = Dict.SequenceEqual(Dict_BM);