简体   繁体   中英

How can i get property names from an Expression tree?

My method is

    public Task<Product> GetProduct(int productId, params Expression<Func<Product, object>>[] properties)
    {

      var member = properties[0].Body as MemberExpression;
      var v = member.Member.Name;

    }

i can get a single property name by using the appropriate index

 var member = properties[0].Body as MemberExpression;
 var v = member.Member.Name;

But this is not what i want. I would love to get all property names and string.join them with linq.

How can i do that?

Use as operator and then filter the ones which were not properties. If you use casting, it will throw exception but as will just return null.

var all =     
string.Join(", ", properties
.Select(x =>
    x.Body as MemberExpression))
.Where(x => x != null)
.Select(x =>
    x.Member.Name));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM