mercredi 4 juillet 2018

Get Value of Property inside a Lambda Expression using Reflection

I have an object called SearchDetails which contains:

SearchDetails: 
{ ColName: "StrName"
  SearchVal" "mega" }

I am making a generic lambda expression by using reflection method.

    public dynamic searchMethod(object SearchDetails)
    {
        ParameterExpression Parameter = Expression.Parameter(typeof(SearchDetails), "x");

        var searchCol = Expression.Property(
         Parameter,
         SearchDetails.GetType().GetProperty("ColName")

       );
        var colVal = Expression.Property(
          Parameter,
          SearchDetails.GetType().GetProperty("SearchValue").Name
        );

       Expression contMethod = Expression.Call(searchCol, "Contains", null, colVal);
        Expression<Func<SearchDetails, bool>> lambda =
           Expression.Lambda<Func<SearchDetails, bool>>(contMethod, Parameter);

        return lambda;
    }

The problem is that I am getting lambda expressions as follow:

{x => x.ColName.Contains(x.SearchValue)}

However, I want it to be like this: {x => x.StrName.Contains("megabrand")}. I cannot access the value of the properties: ColName and SearchValue. How to solve this problem?





Aucun commentaire:

Enregistrer un commentaire