Is there an easy way to merge C# anonymous objects

后端 未结 2 1337
有刺的猬
有刺的猬 2020-12-05 02:47

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

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


        
2条回答
  •  温柔的废话
    2020-12-05 03:14

    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)item1;
        var dictionary2 = (IDictionary)item2;
        var result = new ExpandoObject();
        var d = result as IDictionary; //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.

提交回复
热议问题