如何比较c#中的两个字典,并在验证后获得True和False的输出

时间:2013-08-14 03:45:47

标签: c# dictionary comparison output

我想比较c#中的两个词典,以便将输出设为'True'和'False'。这是我到目前为止的代码:

var dict3 = Dict.Where(entry => Dict_BM[entry.Key] != entry.Value)
                .ToDictionary(entry => entry.Key, entry => entry.Value);

我有两个不同的词典名称为'Dict'和'Dict_BM',我想比较这两个词典。请建议最好的方法将输出设为'True'和'False' 谢谢!

2 个答案:

答案 0 :(得分:4)

我认为这是比较两个字典并返回结果是真还是假的最简单方法。

这个逻辑对我有用。

                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");
                }

希望这对你有帮助。

答案 1 :(得分:1)

如果你想构造一个新的字典,其中每个键的值是一个布尔值,表明两个源字典中的条目是否相等,试试这个:

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);