0

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);
}
Kjartan
  • 18,591
  • 15
  • 71
  • 96
SSK
  • 783
  • 3
  • 18
  • 42
  • Hi! Try to look here http://stackoverflow.com/questions/245055/how-do-you-get-the-all-properties-of-a-class-and-its-base-classes-up-the-hierar – Ilia Maskov Apr 20 '15 at 09:33
  • if `AClassAddress`and `BClassAddress` are identical, can't you simply reuse the class? If so, you can add a `Clone` method that duplicate the object. This may require a bit more code, but will perform faster than any dynamic or automatic technic – Steve B Apr 20 '15 at 09:40
  • It might not be the same, for example i might have 3 properties in AClassAddress where as in BClass i might have only 2 – SSK Apr 20 '15 at 09:59
  • You can check if a property is an IEnumerable and if so, enumerate through it and us the same piece of code than yours recursively. – LInsoDeTeh Jul 13 '15 at 08:46

0 Answers0