更改Lambda表达式更深一层 [英] Alter Lambda Expression to go one level deeper

查看:87
本文介绍了更改Lambda表达式更深一层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的方法:

Suppose I have a method like this:

public void MultiDropDown<T>(Expression<Func<T, DropDownModel<DropDownItem>>> expression)
{

   // Here i want to get more specific with the expression selector
   // Suppose it was passed like this: 
   //                                  MultiDropDown(x => x.MyDropDown);
   // I need to alter `expression` and go deeper:    x => x.MyDropDown.Title;
   // And then use the new expression for other stuff...
}

解决方案

谢谢您!

Solution

Thanks to svick !

public void MultiDropDown<T>(Expression<Func<T, DropDownModel<DropDownItem>>> expression)
{
        // 1. Build a new expression and select the final property
        Expression<Func<DropDownModel<DefaultDropDownItem>, object>> childExpression = x => x.Title;
        // 2. Extract property name
        var propName = (childExpression.Body as MemberExpression).Member.Name;
        // 3. Create a MemberExpression selection from parent's Body
        var expressionProperty = Expression.Property(expression.Body, propName);
        // 4. Finally create a Lambda Expression
        var refinedExpression = Expression.Lambda<Func<TModel, object>>(expressionProperty, expression.Parameters);
}

进行操作1和2.只是为了避免使用标题"字符串,而是依赖于强类型化模型.

Operations 1. and 2. were done just for avoiding "Title" string and relying on Strongly Typed model instead.

推荐答案

您需要创建一个表达式,该表达式采用查询的Body并访问其上的给定属性.然后,您需要重新构建lambda表达式.整个过程看起来像这样:

What you need is to create an expression that takes the Body of your query and accesses the given property on it. Then you need to build back the lambda expression. The whole thing looks like this:

var titleExpression = Expression.Lambda<Func<T, string>>(
    Expression.Property(expression.Body, "Title"), expression.Parameters);

这篇关于更改Lambda表达式更深一层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆