Access nested properties with dynamic lambda using Linq.Expression

前端 未结 4 2533
说谎
说谎 2021-02-20 10:39

Let\'s assume that I have two classes:

class person
{
    int ID
    string name
    Address address
}
class address
{
    int ID
    string street
    string co         


        
4条回答
  •  暖寄归人
    2021-02-20 11:32

    Here's a more generic version of LukLed's answer:

        protected MemberExpression NestedExpressionProperty(Expression expression, string propertyName)
        {
            string[] parts = propertyName.Split('.');
            int partsL = parts.Length;
    
            return (partsL > 1) 
                ? 
                Expression.Property( 
                    NestedExpressionProperty(
                        expression, 
                        parts.Take(partsL - 1)
                            .Aggregate((a, i) => a + "." + i)
                    ), 
                    parts[partsL - 1]) 
                :
                Expression.Property(expression, propertyName);
        }
    

    You can use it like this:

    var paramExpression = Expression.Parameter(this.type, "val");
    var firstProp = NestedExpressionProperty(paramExpression,"address.street");
    

提交回复
热议问题