Is there an easy way to merge C# anonymous objects

后端 未结 2 1357
有刺的猬
有刺的猬 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:12

    Using TypeDescriptor

    As mentioned in comments, Luke Foust solution does not work with anonymous types. The cast to Dictionary does not work, I propose to construct the Dictionaries using the TypeDescriptor.GetProperties method:

    public static dynamic CombineDynamics(object object1, object object2)
    {
      IDictionary dictionary1 = GetKeyValueMap(object1);
      IDictionary dictionary2 = GetKeyValueMap(object2);
    
      var result = new ExpandoObject();
    
      var d = result as IDictionary;
      foreach (var pair in dictionary1.Concat(dictionary2))
      {
        d[pair.Key] = pair.Value;
      }
    
      return result;
    }
    
    private static IDictionary GetKeyValueMap(object values)
    {
      if (values == null)
      {
        return new Dictionary();
      }
    
      var map = values as IDictionary;
      if (map == null)
      {
        return map;
      }
    
      map = new Dictionary();
      foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))
      {
        map.Add(descriptor.Name, descriptor.GetValue(values));
      }
    
      return map;
    }
    

    It's now working with anonymous types:

    var a = new {foo = "foo"};
    var b = new {bar = "bar"};
    
    var c = CombineDynamics(a, b);
    
    string foobar = c.foo + c.bar;
    

    Notes:

    My GetKeyValueMap method is based on the RouteValueDictionary class (System.Web.Routing). I've rewritten it (using ILSpy to disassemble it) because I think that a System.Web class has nothing to do with object merging.

提交回复
热议问题