Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing dynamic objects in C#

Tags:

c#

dynamic

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.Name = "Marcus";
obj1.Age = 39;
obj1.LengthInMeters = 1.96;

dynamic obj2 = AMethodReturningADynamic();
obj2.Name = "Marcus";
obj2.Age = 39;
obj2.LengthInMeters = 1.96;

Assert.AreEqual(obj1, obj2); // ?

Or is there a way to get the actual properties and their values as lists? To create an ExpandoObject from a dynamic type for example?

like image 364
Marcus Hammarberg Avatar asked Aug 27 '11 16:08

Marcus Hammarberg


People also ask

How to compare dynamic object in c#?

You have to implement IComparable-Interface. Then you have the appropriate functions needed from . NET/C# to compare two objects with each other.

What is comparer in c#?

Objects Comparer is an object-to-object comparer that allows you to compare objects recursively member by member and defines custom comparison rules for certain properties, fields, or types. Objects Comparer can be considered as ready to use a framework or as an idea for similar solutions.

Can we compare two objects in C#?

In C# objects can be compared with the == operator, with the Equals(Object) member, with the Object. Equals(Object, Object) method or using custom comparators that implement one of or more of the IEquatable<T> , IComparable , IStructuralEquatable or IStructuralComparable interfaces. There's also a Object.

What is dynamic object in C#?

Dynamic objects expose members such as properties and methods at run time, instead of at compile time. This enables you to create objects to work with structures that do not match a static type or format.


1 Answers

ExpandoObject implements ICollection<KeyValuePair<string, object>> (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<KeyValuePair<string,object>>)obj1;
    var obj2AsDict = (IDictionary<string,object>)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;
}
like image 170
dlev Avatar answered Sep 20 '22 13:09

dlev