Nicholas Magnussen
Nicholas Magnussen

Reputation: 769

Convert MemberExpression to string

In the following method I'm trying to make an Expression using the List<string>().Contains() method.

The problem is that the value I need to check if exists in the list is not of type string and therefore I need to convert it.

private static Expression<Func<Books, bool>> GenerateListContainsExpression(string propertyName, List<string> values)
    {          
        var parameter = Expression.Parameter(typeof(Books), "b");
        var property = Expression.Property(parameter, propertyName);
        var method = typeof(List<string>).GetMethod("Contains");
        var comparison = Expression.Call(Expression.Constant(values), method, Expression.Constant(Expression.Convert(property, typeof(string))));

        return Expression.Lambda<Func<Books, bool>>(comparison, parameter);
    }

This gives me an error saying:

"No coercion operator is defined between types 'System.Nullable`1[System.Int32]' and 'System.String'."

It is not guarantied that the value is of the type int?

Is there any way to do this?

Upvotes: 1

Views: 2324

Answers (1)

Yacoub Massad
Yacoub Massad

Reputation: 27861

You can invoke ToString on the property value first. Here is an example of how you can do that:

private static Expression<Func<Books, bool>> GenerateListContainsExpression(
    string propertyName,
    List<string> values)
{
    var parameter = Expression.Parameter(typeof(Books), "b");
    var property = Expression.Property(parameter, propertyName);

    var contains_method = typeof(List<string>).GetMethod("Contains");

    var to_string_method = typeof(object).GetMethod("ToString");

    var contains_call = Expression.Call(
        Expression.Constant(values),
        contains_method,
        Expression.Call(property, to_string_method));

    return Expression.Lambda<Func<Books, bool>>(contains_call, parameter);
}

Upvotes: 2

Related Questions