[Solved] How to get the value of each string inside a List in c# using reflection


Before you read any further I suggest you check out AutoMapper. AutoMapper is designed to map data from one type to another. From what I see, this is what you are trying to accomplish.

One note of caution, AutoMapper does not perform a deep copy on lists. So if you modify the list on the source object, it will affect the list on the destination object.

A shallow copy is straight forward, just copy the list directly, the same as you are with your primitive and nullable types.

Something else to consider with your code. You are checking the property names, but not the types of the two objects. What if you have int Id on one class with string Id on the other?

If you must have a deep copy of the list, it gets a little more complex. But here is what I came up with (note: this is not a true deep copy, because the members of the list are not cloned):

else if (dataBasePropInfo.PropertyType.IsGenericType)
{
    var args = dataBasePropInfo.PropertyType.GetGenericArguments();
    var lstType = typeof (List<>).MakeGenericType(args);
    if (lstType.IsAssignableFrom(dataBasePropInfo.PropertyType))
    {
        PropertyInfo modelPropInfo = modelObjectType.GetProperty(dataBasePropInfo.Name);
        var target = Activator.CreateInstance(lstType);
        var source = modelPropInfo.GetValue(modelObject);
        lstType.InvokeMember("AddRange", BindingFlags.InvokeMethod, null, target, new[] {source});

        dataBasePropInfo.SetValue(dataBaseObject, target);
    }
    else
    {
        UpdateObjectFrom(dataBasePropInfo.GetValue(dataBaseObject, null), modelObjectType.GetProperty(dataBasePropInfo.Name).GetValue(modelObject, null));
    }
}

Recommended reading: How to: Examine and Instantiate Generic Types with Reflection

Another option

You could use a combination of reflection and serialization.

  1. Serialize your source object to a stream
  2. Deserialize a new copy of your source object (the new object will not share any of the references of the original source)
  3. Copy properties from source-clone to target using: dataBasePropInfo.SetValue(dataBaseObject,
    modelPropInfo.GetValue(modelObject));

1

solved How to get the value of each string inside a List in c# using reflection