[英]LINQ Expression of the Reference Property
我想獲取參考屬性的LINQ表達式
我需要將Lambda表達式獲取為groupCol => groupCol.Role.Name
我已經嘗試過使用表達式,但沒有成功,它將與groupCol => groupCol.MenuText一起使用,但不適用於引用類型
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;}
}
提前致謝
您需要一次執行一項操作:
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
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.