2

I need to construct a dynamic lambda expression like: m => m.Data[0].Name

I have model classes:

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 });
    }
}

And I am trying to consruct it like so:

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);

However, my problem is that I don't know how to use '.getItem(0)' properly, as it gives me exception:

Instance property 'Data.get_Item(0).Name' is not defined for type 'GridModelList'

Any help on how to build the needed expression m => m.Data[0].Name would be greatly appreciated!!

2
  • Any reason you aren't just using an ordinary lambda e.g. Func<TGridModel, object> lambda = m => m.Data[0].Name; ? Commented Apr 8, 2014 at 12:52
  • Hi @Iridium, I have different 'GridModels' I have to deal with so I need to construct these expressions dynamically using reflection. The end goal is so I can use MVC HtmlHelper methods like TextboxFor Commented Apr 8, 2014 at 13:08

1 Answer 1

3

You need use Expression.Property for index property like this

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");

and then

Expression<Func<TGridModel, object>> exp = Expression.Lambda<Func<TGridModel, object>>(fieldNameExpr, fieldName);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Grundy. I am new to lambda expressions and literally spent hours trying to get it right. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.