Search code examples
c#.netexpressionexpression-trees

Creating Lambda Expression for Generic Objects


I need to create Expression<Func<TModel, TValue>> from my model.

How to access the property in the model:

ViewModel.CustomFieldCollection[1].PrimaryFields[3].Value

where 1 & 3 are the indexes which will updated at runtime.

I am trying to creating an expression, to be passed to a HtmlHelper, to generate an HtmlString for me.

var viewModelExpParam = Expression.Parameter(typeof(ViewModel));

var fieldParam = Expression.Property(viewModelExpParam, "CustomFieldCollection[1]");

var expression = Expression.Lambda<Func<TModel, TValue>>(fieldParam, viewModelExpParam);

But the above code gives the error while creating fieldParam, as it is not the object but a collection object.

Can i generate an expression to access ViewModel.CustomFieldCollection[1].PrimaryFields[3].Value in HtmlHelper at runtime?


Solution

  • You could acces indexxed member via Item property (it's just a sample code, i haven't tried it out, you haven't provided any code for it :)):

    var customFieldCollection = Expression.Property(viewModelExpParam,"CustomFieldCollection");
    var fieldParam = Expression.Property(customFieldCollection , "Item", 
                             new Expression[] { Expression.Constant(1) });
    

    And than:

    var primaryFields = Expression.Property(fieldParam,"PrimaryFields");
    var primaryFieldItem = Expression.Property(primaryFields , "Item", 
                                 new Expression[] { Expression.Constant(3) });
    var value = Expression.Property(primaryFieldItem, "Value");
    
    var expression = Expression.Lambda<Func<TModel, TValue>>(value,  viewModelExpParam);