tags:

views:

34

answers:

3

I use the following method to create a SelectListItem object from any other object:

        public static SelectListItem ToSelectListItem<T, TResult, TResult2>(T obj, Expression<Func<T, TResult>> value, Expression<Func<T, TResult2>> text)
        {
            string strValue = String.Empty;
            string strText = String.Empty;

            if (value != null)
                strValue = (value.Body as MemberExpression).Member.Name;

            if (text != null)
                strText = (text.Body as MemberExpression).Member.Name;
            ...
         }

I use this method like this:

SelectListItem item = ToSelectListItem(obj, x => x.ID, x => x.Name);

And it works fine. However, when I specify a property from an associated object all I get is the name of the property

SelectListItem item = ToSelectListItem(obj, x => x.ID, x => x.Profile.Name);

The property name I'm able to get from 'x => x.Profile.Name' is only 'Name' and what I really wanted to get was 'Profile.Name'.

Any suggestions would be appreciated.

+2  A: 

This post details clearly how to achieve this: http://geekswithblogs.net/EltonStoneman/archive/2009/11/05/retrieving-nested-properties-from-lambda-expressions.aspx

Jay
…and for a good laugh, notice the comment below the post: "is that PHP?"
Jay
This post helped me find a better solution
Raphael
A: 

It's much easier to use Func instead of Expression<>

To manipulate the property all I have to do is invoke it:

expression.Invoke(obj);
Raphael
+1  A: 

Or you can use

expression.Compile().Invoke(obj)

if you want to use Expression<>

ThiagoAlves