Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merging two objects in C#

Tags:

c#

.net

I have an object model MyObject with various properties. At one point, I have two instances of these MyObject: instance A and instance B. I'd like to copy and replace the properties in instance A with those of instance B if instance B has non-null values.

If I only had 1 class with 3 properties, no problem, I could easily hard code it (which is what I started doing). But I actually have 12 different object models with about 10 properties each.

What's good way to do this?

like image 309
frenchie Avatar asked Jan 02 '12 15:01

frenchie


People also ask

How do you combine two objects?

To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.

How do I merge two objects in blender?

Once it's selected, hold down “Shift” and left-click the other objects you want to join. The last object you select will be the parent. Once everything you want to be joined is selected, click on the “Join” button in the Object menu (as shown in the above image) or simply press “Ctrl + J”.

What is an object in C# with example?

Everything in C# is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake. A Class is like an object constructor, or a "blueprint" for creating objects.


2 Answers

Update Use AutoMapper instead if you need to invoke this method a lot. Automapper builds dynamic methods using Reflection.Emit and will be much faster than reflection.'

You could copy the values of the properties using reflection:

public void CopyValues<T>(T target, T source) {     Type t = typeof(T);      var properties = t.GetProperties().Where(prop => prop.CanRead && prop.CanWrite);      foreach (var prop in properties)     {         var value = prop.GetValue(source, null);         if (value != null)              prop.SetValue(target, value, null);     } } 

I've made it generic to ensure type safety. If you want to include private properties you should use an override of Type.GetProperties(), specifying binding flags.

like image 73
Bas Avatar answered Sep 18 '22 15:09

Bas


I have tried Merge Two Objects into an Anonymous Type by Kyle Finley and it is working perfect.

With the TypeMerger the merging is as simple as

var obj1 = new {foo = "foo"};  var obj2 = new {bar = "bar"};  var mergedObject = TypeMerger.MergeTypes(obj1 , obj2 ); 

That's it you got the merged object, apart from that, there is a provision to ignore specific properties too. You can use the same thing for MVC3 too.

like image 26
Naveen Vijay Avatar answered Sep 20 '22 15:09

Naveen Vijay