使用对列表项的引用构造C#Lambda表达式

时间:2014-04-08 12:46:10

标签: c# lambda

我需要构建一个动态的lambda表达式,如:m => m.Data[0].Name

我有模型类:

public class GridItem
{
    [Required]
    [Display(Name = "Name")]
    public string Name{ get; set; }

    [Required]
    [Display(Name = "Address")]
    public string Password { get; set; }

    [Display(Name = "Age")]
    public string Age{ get; set; }
}

public class GridModelList
{
    public List<GridItem> Data { get; set; }

    public GridModelList()
    {
        Data = new List<GridItem>();
        Data.Add(new GridItem() {Name = "Name", Address= "Address", Age= 1 });
        Data.Add(new GridItem() {Name = "Name", Address= "Address", Age= 1 });
    }
}

我正试图像这样建构:

ParameterExpression fieldName = Expression.Parameter(typeof(TGridModel), "m");
MemberExpression fieldExpr = Expression.Property(fieldName, "m.Data.getItem(0).Name");
Expression<Func<TGridModel, object>> exp = Expression.Lambda<Func<TGridModel, object>>(fieldExpr, fieldName);

然而,我的问题是我不知道如何正确使用'.getItem(0)',因为它给了我例外:

  

没有为类型'GridModelList'定义实例属性'Data.get_Item(0).Name'

非常感谢有关如何构建所需表达式m => m.Data[0].Name的任何帮助!!

1 个答案:

答案 0 :(得分:3)

您需要像这样使用Expression.Property for index property

ParameterExpression fieldName = Expression.Parameter(typeof(TGridModel), "m");

var fieldDataExpr = Expression.Property(fieldName, "Data");
var fieldExpr = Expression.Property(fieldDataExpr, "Item", Expression.Constant(0));
var fieldNameExpr = Expression.Property(fieldExpr, "Name");

然后

Expression<Func<TGridModel, object>> exp = Expression.Lambda<Func<TGridModel, object>>(fieldNameExpr, fieldName);