Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging anonymous types

How can I merge two anonymous types, so that the result contains the properties of both source objects?

var source1 = new {     foo = "foo",     bar = "bar" }  var source2 = new {     baz = "baz" }  var merged = Merge(source1, source2) // <-- here's where the magic should happen  // merged:  // { //      foo = "foo", //      bar = "bar", //      baz = "baz" // } 
like image 544
davehauser Avatar asked Jul 19 '11 22:07

davehauser


1 Answers

So here's, what I finally came up with (inspired by @BlueMonkMN's answer):

public dynamic Merge(object item1, object item2) {     if (item1 == null || item2 == null)         return item1 ?? item2 ?? new ExpandoObject();      dynamic expando = new ExpandoObject();     var result = expando as IDictionary<string, object>;     foreach (System.Reflection.PropertyInfo fi in item1.GetType().GetProperties())     {         result[fi.Name] = fi.GetValue(item1, null);     }     foreach (System.Reflection.PropertyInfo fi in item2.GetType().GetProperties())     {         result[fi.Name] = fi.GetValue(item2, null);     }     return result; } 
like image 67
davehauser Avatar answered Sep 17 '22 12:09

davehauser