简体   繁体   English

比较 C# 中深度嵌套字典的 2 个对象

[英]Compare 2 objects which are deep nested dictionaries in C#

I have a deep nested dictionaries:我有一个很深的嵌套字典:

var a1 = new Dictionary<string, Dictionary<string, Dictionary<string, Person>>>();
var a2 = new Dictionary<string, Dictionary<string, Dictionary<string, Person>>>();

where Person is some data structure containing members like name , family , age ...其中Person是一些包含成员的数据结构,如namefamilyage ...

public class Person
{
    public string name{ get; set; }
    public string family{ get; set; }
    public int age { get; set; }
}

I want to compare between a1 and a2 and especially between the Person's members.我想在 a1 和 a2 之间进行比较,尤其是在Person's成员之间。 What is the best way to do that?最好的方法是什么?

There is no out of the box solution that I can think of as deep comparison of objects is not given by libraries just because it is not a trivial task to define in a generic way that would cover most use cases.我认为没有开箱即用的解决方案,因为库没有提供对象的深度比较,因为以涵盖大多数用例的通用方式定义并不是一项微不足道的任务。 For you specific one it is fairly easy to implement.对于您特定的一个,它很容易实现。 You just need to write 2 methods on that compares dictionaries and one that compares the objects:您只需要编写 2 个比较字典的方法和一个比较对象的方法:

void Compare<T, G>(Dictionary<T, G> first, Dictionary<T, G> second)
{
    foreach (var item in first)
    {
        if (!second.ContainsKey(item.Key)) Assert.Fail();

        var secondValue = second[item.Key];

        Compare(item.Value, secondValue);
    }
}

void Compare<T>(T first, T second)
{
    if (first is Dictionary<string, Dictionary<string, Dictionary<string, Person>>> f)
    {
        Compare(f, (Dictionary<string, Dictionary<string, Dictionary<string, Person>>>)(object)second);
    }
    else if (first is Dictionary<string, Dictionary<string, Person>> f1)
    {
        Compare(f1, (Dictionary<string, Dictionary<string, Person>>)(object)second);
    }
    else if (first is Dictionary<string, Person> f2)
    {
        Compare(f2, (Dictionary<string, Person>)(object)second);
    }
    else
    {
        foreach (var property in typeof(T).GetRuntimeProperties())
        {
            Assert.AreEqual(property.GetValue(first), property.GetValue(second));
        }
    }
}

there is a lot not covered by this code snippet but you can expand of it to match your use cases.此代码段没有涵盖很多内容,但您可以扩展它以匹配您的用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM