Houman
Houman

Reputation: 66320

How to retrieve the value of a number of properties?

  1. I have a List collection that hold a number of property names.

  2. MyViewModel is a class that holds all possible properties to be shown on a view.

  3. Now I would like go through a collection of MyViewModel and only get the values of all those properties that were defined previously in step 1).

I think I have to use reflection.

I could get the property name like this:

public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
    var body = (MemberExpression) expression.Body;
    return body.Member.Name;
}

However how do I now utilise this further to go through the collection and get the values for only the properties I have defined in step 1?

Many thanks.

Upvotes: 2

Views: 64

Answers (1)

Schroedingers Cat
Schroedingers Cat

Reputation: 3129

If you have a property name you need to do ( roughly - I cannot test it out ATM )

thing.GetType().Properties(propname).GetValue(thing,null);

which should return you the value of the 'propname' property on the 'thing' object.

Upvotes: 1

Related Questions