Add Property values to Object from Dictionary

2.8k views Asked by At

So I have an Object called PaypalTransaction here is the begining of it , don't need to show all properties to explain question.

public class PaypalTransaction
{
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string custom { get; set; }
    public string payer_email { get; set; }
    ....
    ....
}

now my questions is , I have a foreach loop that has each key as a string

PaypalTransaction trans = new PaypalTransaction();
foreach(string key in keys)
{
    // key = "first_name" ,  or "last_name , or "custom"
    // how would I set the value of trans based on each key
    //  so when key = "first_name , I want to set trans.first_name
    // something like trans.PropName[key].Value = 
    // I know that code isn't real , but with reflection i know this is possible

 }
1

There are 1 answers

2
danish On BEST ANSWER

You can get the collection of properties from trans object and cache it before the loop. The you can loop through that and set the values of appropriate properties. Following sample may help:

PaypalTransaction trans = new PaypalTransaction();

            PropertyInfo[] properties = trans.GetType().GetProperties();

            foreach (string key in keys)
            {
                properties.Where(x => x.Name == key).First().SetValue(trans, "SetValueHere");

            }

You may need to optimize the code above for performance and other possible exceptions.