Search code examples
c#linqlambdaexpression-trees

Casting/converting an expression back to a lambda of Func<Foo,bool> (after serialization)


I am trying to serialize and deserialize a Func[Foo,bool]. I'm using Serial.Linq for the serialization and for it's part it seems to work, but I can't get my lambda predicate reassembled. Most of it probably stems from my poor understanding of expression trees.

I've tried passing type parameters in different orders and Expression.Convert to Func[Foo,bool] but nothing I try seems to work.

using System;
using Serialize.Linq.Serializers;
using System.Linq.Expressions;


public class Foo
{
        public string Bar {get; set;}
}

public class Program
{

    public static void Main()
    {
        // Step 1 Serialize it
        Expression<Func<Foo,bool>> bark = foo => foo.Bar.Contains("ruff");
        var expressionSerializer = new Serialize.Linq.Serializers.ExpressionSerializer(new Serialize.Linq.Serializers.JsonSerializer());
        var serializedQuery = expressionSerializer.SerializeText(bark);

        // Step 2 Deserialize it
        var barkExpression = expressionSerializer.DeserializeText(serializedQuery);
        var barkExpressionReturnArgument = Expression.Parameter(typeof(bool));
        var barkExpressionArgument = Expression.Parameter(typeof(Foo));
        // var convertedExpression = Expression.Convert(barkExpression, typeof(Func<Foo,bool>));

        // How do I get bark back? I've tried a few variations here and can't quite get it. :(
        var barkFunction = Expression.Lambda<Func<Foo, bool>>(barkExpression, barkExpressionArgument).Compile();

        Console.WriteLine("Hello World");


    }

}

https://dotnetfiddle.net/MWNeol


Solution

  • I figured it out. I was trying to do too much, I didn't need the Parameter expressions.

    Just this after deserialization:

    var barkFunction = ((Expression<Func<Foo, bool>>)barkExpression).Compile()