将C#中的两个词典与字符串进行比较,Dictionary <string,object =“”>&gt;

时间:2016-09-02 01:25:08

标签: c# dictionary

我有两个词典,我想将它们相互比较,它们的类型为Dictionary&gt;

我尝试使用foreach循环,但它根本无法正常工作。最好的方法是什么?

foreach (KeyValuePair<string, Dictionary<string, object>> entry1 in dict1)
{
    foreach (KeyValuePair<string, Dictionary<string, object>> entry2 in dict2)
    {
        if (entry1.key = entry2.key)
        {
            if (entry1.Value["Number"]==entry2.Value["Number"])
            {
                Console.WriteLine("Comparison successful")
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

public static Boolean CompareDictionary(Dictionary<string, object> D1, Dictionary<string, object> D2)
{
    if (D1 == null && D2 == null) return true;
    else if (D1 == null || D2 == null) return false;

    if (D1.Count != D2.Count) return false;    
    if (D1.Keys.Except(D2.Keys).Any()) return false;
    if (D2.Keys.Except(D1.Keys).Any()) return false;

    foreach (string Key in D1.Keys)
    {
        if (!D2.ContainsKey(Key)) return false;
        if (D1[Key] != D2[Key]) return false;
    }
    return true;
}

答案 1 :(得分:0)

这是:

> n
[1]  7 43 29 13  8