Is there an easy way to merge C# anonymous objects

If you truly do mean dynamic in the C# 4.0 sense, then you can do something like:

static dynamic Combine(dynamic item1, dynamic item2)
{
    var dictionary1 = (IDictionary<string, object>)item1;
    var dictionary2 = (IDictionary<string, object>)item2;
    var result = new ExpandoObject();
    var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary

    foreach (var pair in dictionary1.Concat(dictionary2))
    {
        d[pair.Key] = pair.Value;
    }

    return result;
}

You could even write a version using reflection which takes two objects (not dynamic) and returns a dynamic.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)