0

I have a list of a class object

lets say the class is structured like this

    class DataEntity 
    {
        public string col1 { get; set; }
        public string col2 { get; set; }
        public string col3 { get; set; }
    }

so the list would be

List<DataEntity> list = new List<DataEntity>

So here is my issue I need to loop through list and modify the value of a specific property..but I don't know what property need to be modified until run time.

so lets say there is a Method that converts the list and the property name to be modified is passed in as a string value

public List<DataEntity> Convert (List<DataEntity> list, string propertyName, string appendedValue)
{ 

}

SO my question is how can I loop though that list and for the propertyName entered append the appendedValue to that properties value

I know I can get the proeprties values using reflection like this

 Type type = dataEntity.GetType();
 foreach (PropertyInfo pi in type.GetProperties())
 {    
 }

but I'm not sure how that can be leveraged to target a specific property for appending at runtime.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
Bastyon
  • 1,571
  • 4
  • 21
  • 28
  • 2
    Did you look at the `GetProperty()` method? Or just search the array of `PropertyInfo` objects returned by `GetProperties()` for the property having the name you want? You should be more specific about what research you've already done, what you found, and why you aren't able to use that information to solve your problem yet. – Peter Duniho Jan 24 '15 at 23:59
  • 1
    Flagged your comment as nonconstructive. Next time either answer the question or move on. There was plenty of data to help formulate a proper response as user3980820 was kind enough to do. – Bastyon Jan 25 '15 at 02:48
  • 1
    See that would be a helpful comment. Certainly more so than lecturing me. – Bastyon Jan 25 '15 at 03:11

1 Answers1

6

you should use something like this :

PropertyInfo propertyInfo;
foreach (YourClass C in list)
{
    propertyInfo = C.GetType().GetProperty(propertyName);
    propertyInfo.SetValue(C, Convert.ChangeType(appendedValue, propertyInfo.PropertyType), null);
}
return list;

For more information you can check these links :Setting a property, Getting property value

Community
  • 1
  • 1
Abdessabour Mtk
  • 3,895
  • 2
  • 14
  • 21