Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从MemberExpression获取链接属性名称_C#_Linq - Fatal编程技术网

C# 从MemberExpression获取链接属性名称

C# 从MemberExpression获取链接属性名称,c#,linq,C#,Linq,我正在为MVC创建一个表单生成器,我想用以下方式模拟Razor对链接属性的处理: builder.TextBoxFor(x => x.User.Email); 这将以与Razor相同的方式产生以下结果: <input id="User_Email" name="User.Email" type="textbox" /> 我如何调整这一点,使x.User.Email产生User.Email,而不仅仅是Email,就像现在这样?您需要一点递归: private static s

我正在为MVC创建一个表单生成器,我想用以下方式模拟Razor对链接属性的处理:

builder.TextBoxFor(x => x.User.Email);
这将以与Razor相同的方式产生以下结果:

<input id="User_Email" name="User.Email" type="textbox" />

我如何调整这一点,使
x.User.Email
产生
User.Email
,而不仅仅是
Email
,就像现在这样?

您需要一点递归:

private static string GetPropertyPath<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression)
{
    var propertyPath = new Stack<string>();
    var body = (MemberExpression)expression.Body;

    do
    {
        propertyPath.Push(body.Member.Name);

        // this will evaluate to null when we will reach ParameterExpression (x in "x => x.Foo.Bar....")
        body = body.Expression as MemberExpression;
    }
    while (body != null);

    return string.Join(".", propertyPath);
}
私有静态字符串GetPropertyPath(表达式)
{
var propertyPath=新堆栈();
var body=(MemberExpression)expression.body;
做
{
propertyPath.Push(body.Member.Name);
//当我们到达ParameterExpression(x=>x.Foo.Bar中的x…)时,这将计算为null
body=body.Expression作为MemberExpression;
}
while(body!=null);
返回字符串.Join(“.”,propertyPath);
}
private static string GetPropertyPath<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression)
{
    var propertyPath = new Stack<string>();
    var body = (MemberExpression)expression.Body;

    do
    {
        propertyPath.Push(body.Member.Name);

        // this will evaluate to null when we will reach ParameterExpression (x in "x => x.Foo.Bar....")
        body = body.Expression as MemberExpression;
    }
    while (body != null);

    return string.Join(".", propertyPath);
}