I have a class like below, in which I am trying to assign the property values from AClass to BClass:
public class AClass
{
public string Name { get; set; }
public int NameID { get; set; }
public int Age { get; set; }
public String DateOfBirth { get; set; }
public List<AClassAddress> Addresses { get; set; }
}
public class AClassAddress
{
public string Street;
public string City;
public string State;
public string Country;
}
public class BClass
{
public int NameID { get; set; }
public int Age { get; set; }
public List<BClassAddress> Addresses { get; set; }
}
public class BClassAddress
{
public string Street;
public string City;
public string State;
public string Country;
}
So far I have a code below to assign the property. At the root level, it is working fine all the properties are getting assigned from source to destination, but when it comes to Addresses, which is a Collection with this AClass and BClass, it is not getting populated. Is there anyway to achieve this efficiently?
AClass source = new AClass();
// Getting some test data from JSON
source = JsonConvert.DeserializeObject<AClass>(strJSonString);
BClass dest = new BClass();
Type typeDest = dest.GetType();
Type typeSrc = source.GetType();
var results =
from srcProp in typeSrc.GetProperties()
let targetProperty = typeDest.GetProperty(srcProp.Name)
where srcProp.CanRead
&& targetProperty != null
// && (targetProperty.GetSetMethod(true) != null
// && !targetProperty.GetSetMethod(true).IsPrivate)
&& (targetProperty.GetSetMethod().Attributes & MethodAttributes.Static) == 0
&& targetProperty.PropertyType.IsAssignableFrom(srcProp.PropertyType)
select new { sourceProperty = srcProp, targetProperty = targetProperty };
foreach (var props in results)
{
props.targetProperty.SetValue(dest, props.sourceProperty.GetValue(source, null), null);
}