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?
You have to implement IComparable-Interface. Then you have the appropriate functions needed from . NET/C# to compare two objects with each other.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With