Billy Blaze Billy Blaze - 2 months ago 5x
C# Question

Copy data from a List of object to a different Object in C#

My goal is to reduce the code and avoid having to add conditions when my passed list of object gets longer, it can be up to 100+ fields as the project progresses. I have an object of type MyObject

public class MyObject
public string fininstId { get; set; }
public string paymentMethod { get; set; }
public string cardNumber { get; set; }
public string cardExpiry { get; set; }
public string cardCVC { get; set; }
public string AcctName { get; set; }
public string Password { get; set; }
public string mode { get; set; }

another one of type Response

public class Response
public Response();

public string Title { get; set; }
public string Value { get; set; }

and I need all of the data contained in dataList below to be copied to MyObject, knowing that the name of the fields are going to be the same in both MyObject and dataList.

List<Response> dataList = new List<Response>();

/*...populating dataList here ...*/

MyObject request = new MyObject();

foreach (var item in dataList)
switch (item.Title)
case "cardNumber":
request.cardNumber = item.Value;
case "cardExpiry":
request.cardExpiry = item.Value;
case "cardCVC":
request.cardCVC = item.Value;
case "fininstId":
request.fininstId = item.Value;
case "paymentMethod":
request.paymentMethod = item.Value;
case "AcctName":
request.AcctName = item.Value;
case "Password":
request.Password = item.Value;

Is there anyway it can be done dynamically?


You can use reflection and InvokeMember method

For example:

Response item = new Response();
item.Title = "Password";
item.Value = "value";

MyObject request = new MyObject();
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
Type.DefaultBinder, request, new[] {item.Value} );

Or using GetProperty & SetValue

var property = typeof(MyObject).GetProperty(item.Title);
property.SetValue(request, item.Value, null);