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.
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;
}