Comparing dynamic objects in C#

前端 未结 6 2304
不知归路
不知归路 2021-02-13 04:08

What is the best way to compare two arbitrary dynamic objects for equality? For example these two objects.

I.e.

dynamic obj1 = new ExpandoObject();
obj1.         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-13 04:10

    ExpandoObject implements ICollection> (in addition to IDictionary and IEnumerable of the same), so you should be able to compare them property by property pretty easily:

    public static bool AreExpandosEquals(ExpandoObject obj1, ExpandoObject obj2)
    {
        var obj1AsColl = (ICollection>)obj1;
        var obj2AsDict = (IDictionary)obj2;
    
        // Make sure they have the same number of properties
        if (obj1AsColl.Count != obj2AsDict.Count)
            return false;
    
        foreach (var pair in obj1AsColl)
        {
            // Try to get the same-named property from obj2
            object o;
            if (!obj2AsDict.TryGetValue(pair.Key, out o))
                return false;
    
            // Property names match, what about the values they store?
            if (!object.Equals(o, pair.Value))
                return false;
        }
    
        // Everything matches
        return true;
    }
    

提交回复
热议问题