Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to easily merge two anonymous objects with different data structure?

I would like to merge these two anonymous objects:

var man1 = new {
    name = new {
        first = "viet"
    },
    age = 20
};

var man2 = new {
    name = new {
        last = "vo"
    },
    address = "123 street"
};

Into a single one:

var man = new {
    name = new {
        first = "viet",
        last = "vo"
    },
    age = 20,
    address = "123 street"
};

I looked for a solution but found nothing clever.

like image 685
Hoang Viet Avatar asked Sep 20 '25 10:09

Hoang Viet


1 Answers

There's nothing built-in in the C# language to support your use case. Thus, the question in your title needs to be answered with "Sorry, there is no easy way".

I can offer the following alternatives:

  1. Do it manually:

    var man = new {
        name = new {
            first = man1.name.first,
            last = man2.name.first
        },
        age = man1.age,
        address = man2.address
    };
    
  2. Use a class instead of an anonymous type for the resulting type (let's call it CompleteMan). Then, you can

    • create a new instance var man = new CompleteMan(); ,
    • use reflection to collect the properties and values from your "partial men" (man1 and man2),
    • assign those values to the properties of your man.

    It's "easy" in the sense that the implementation will be fairly straight-forward, but it will still be a lot of code, and you need to take your nested types (name) into account.

    If you desperately want to avoid non-anonymous types, you could probably use an empty anonymous target object, but creating this object (var man = new { name = new { first = (string)null, last = (string)null, ...) is not really less work than creating a class in the first place.

  3. Use a dedicated dynamic data structure instead of anonymous C# classes:

    • The Newtonsoft JSON library supports merging of JSON objects.
    • Dictionaries can also be merged easily.
    • ExpandoObjects can be merged easily as well.
like image 54
Heinzi Avatar answered Sep 23 '25 00:09

Heinzi