Linq calculations for indexer properties

var param = Expression.Parameter(typeof(Employee), "t");    
MemberExpression member = Expression.Property(param, "EmployeeName");
var value = Convert.ChangeType(filterProperty.Value, member.Type);
ConstantExpression constant = Expression.Constant(value);
var body = Expression.Or(leftExpr, Expression.Equal(member, constant));

I can easily get expressions for normal properties, but How can I get an expression for indexer properties?

In the class Employee, I have two indexers.

    class Employee
    {
       public string EmployeeName {get;set;}

       public string this[EmployeeTypes empType]
       {
          get
           {
             return GetEmployee(empType);
           }
       }

       public string this[int empNum]
       {
          get
           {
             return GetEmployee(empNum);
           }
        }
    }
+3
source share
1 answer

Use Itemas property name:

var param = Expression.Parameter(typeof(Employee), "t");
MemberExpression member = Expression.Property(param, "EmployeeName");
var body = Expression.Property(param, "Item", Expression.Constant(10));
var lambda = Expression.Lambda<Func<Employee, string>>(body, param);
var compiled = lambda.Compile();

gives the same thing that can be done with

Func<Employee, string> compiled = t => t[10];
+5
source

All Articles