I Have two classes:
Car
{
string Color;
}
ModifiedCar{
string Color;
int Price;
}
I created two object:
var obj1 = new Car{
Color = "red";
}
var obj2 = new ModifiedCar{
Color = "green";
Price = 330442;
}
Now I want to copy matching fields value(which is color field) from obj1 to obj2 without modifying price. Resulting object that I want:
obj2 ={
Color = "red";
Price = 330442;
}
I can do it by obj2.color = obj1.color
, but When the field is more, it will be problematic. I want to know, is there any built-in function or technique by which I can easily achieve this without manually copying each field?
CodePudding user response:
What are you are trying to do is called object to object mapping. There are a set of available libraries in c# to help you do that, most notably Automapper.
You can also use reflection to find the fields you want and map their values across objects, although this approach's performance would not be great.
CodePudding user response:
Here is your solution without any third party library
- Copy below code and paste it into your class
public void GetMappedValues<T1, T2>(T1 source, T2 destination)
{
foreach (PropertyInfo propertyInfo in typeof(T1).GetProperties())
{
typeof(T2).GetMembers()
.OfType<PropertyInfo>()
.FirstOrDefault(p => p.Name == propertyInfo.Name) //exact match property name in source and destination
?.SetValue(destination,
propertyInfo.GetValue(source)); //set value to destination property from source property
}
}
- In caller method
var car = new Car();
car.Color = "Red";
var mcar = new ModifiedCar();
mcar.Price = 100;
mcar.Color = "Blue";
GetMappedValues(car, mcar);
//mcar.Color turn to Red