How to get the full name of a property from lambda

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 as follows:

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

And it works great. However, when I specify a property from a related object, all I get is the name of the property

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

The name of the property that I can get from 'x => x.Profile.Name' is only “Name”, and I really wanted to get “Profile.Name”.

Any suggestions would be appreciated.

+3
source share
3 answers

Or you can use

expression.Compile().Invoke(obj)

if you want to use Expression<>

+2
source

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

To manage a property, all I have to do is call it:

expression.Invoke(obj);
0
source

Source: https://habr.com/ru/post/1754692/


All Articles