Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection help. Make a collection from a class based on its properties?

I need a little help. I am fairly new to reflection. We're using a 3rd party api and it returns a class called "AddressList". It has public properties within it literally called Address1, Address1Name, Address1Desc, Address2, Address2Name, Address2Desc, Address3, Address3Name, Address3Desc,... Address99, Address99Name, Address99Desc.. There are also a couple of other properties. I have a class called "SimpleAddress" that has just the 3 properties (Address, Name, Description). What I want to do is when I get the "AddressList" class returned, I would like to loop AddressDesc1... through AddressDesc99... and whichever ones are not null or empty, I would like to create an instance of "SimpleAddress", populate it's properties, and add it to a List... Can someone point me in the right direction? Obviously this would have been better if "AddressList" was some sort of collection, but unfortunately it is not. It is generated from a return string from a mainframe.

Thanks for any help, ~ck in San Diego

like image 478
Hcabnettek Avatar asked Dec 04 '25 00:12

Hcabnettek


1 Answers

Ick. You could do something like this:

List<SimpleAddress> addresses = new List<SimpleAddress>();

string addressPropertyPattern = "Address{0}";
string namePropertyPattern = "Address{0}Name";
string descPropertyPattern = "Address{0}Desc";

for(int i = 1; i <= MAX_ADDRESS_NUMBER; i++)
{
    System.Reflection.PropertyInfo addressProperty = typeof(AddressList).GetProperty(string.Format(addressPropertyPattern, i));
    System.Reflection.PropertyInfo nameProperty = typeof(AddressList).GetProperty(string.Format(namePropertyPattern, i));
    System.Reflection.PropertyInfo descProperty = typeof(AddressList).GetProperty(string.Format(descPropertyPattern, i));

    SimpleAddress address = new SimpleAddress();

    address.Address = (string)addressProperty.GetValue(yourAddressListObject, null);
    address.Name = (string)nameProperty.GetValue(yourAddressListObject, null);
    address.Description = (string)descProperty.GetValue(yourAddressListObject, null);

    addresses.Add(address);
}
like image 93
Adam Robinson Avatar answered Dec 05 '25 13:12

Adam Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!