Search code examples
c#anonymous-objects

Is there an easy way to merge C# anonymous objects


Let's say I have two anonymous objects like this:

var objA = new { test = "test", blah = "blah" };
var objB = new { foo = "foo", bar = "bar" };

I want to combine them to get:

new { test = "test", blah = "blah", foo = "foo", bar = "bar" };

I won't know what the properties are for both objA and objB at compile time. I want this to be like jquery's extend method.

Anybody know of a library or a .net framework class that can help me do this?


Solution

  • 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.