LINQ表示参考属性 [英] LINQ Expression of the Reference Property

查看:165
本文介绍了LINQ表示参考属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得参考属性的LINQ表达式

I want to get the LINQ Expression of the Reference Property

我需要将Lambda表达式作为groupCol => groupCol.Role.Name

I need to get the Lambda Expression as groupCol=>groupCol.Role.Name

我尝试过使用表达式,但没有成功,这可以在groupCol => groupCol.MenuText中使用,但不能与引用类型一起使用

I have tried with the expression but not succeeded , this will work with groupCol=>groupCol.MenuText but not with reference types

var menu = Expression.Parameter(typeof(Menu), "groupCol");

// getting  Role.Name' is not a member of type exception
var menuProperty = Expression.PropertyOrField(menu, property);

var lambda = Expression.Lambda<Func<Menu, string>>(menuProperty, menu);



public class Menu
{
  public string MenuText {get;set;}
  public Role Role {get;set;}
  public string ActionName {get;set;}
}

public class Role
{
  public string Name {get;set;}
}

在此先感谢

Thanks in Advance

推荐答案

您需要一次完成这一个属性:

You need to do this one property at a time:

private static Expression<Func<Menu, string>> GetGroupKey(string property)
{
    var parameter = Expression.Parameter(typeof(Menu));
    Expression body = null;
    foreach(var propertyName in property.Split('.'))
    {
        Expression instance = body;
        if(body == null)
            instance = parameter;
        body = Expression.Property(instance, propertyName);
    }

    return Expression.Lambda<Func<Menu, string>>(body, parameter);
}

这个答案扩展了 GetGroupKey 方法我在对您之前的问题的回答中向您展示了。

This answer extends the GetGroupKey method I showed you in my answer to your previous question.

这篇关于LINQ表示参考属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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