Search code examples
c#linqlambdaexpression-trees

How do i convert this Func<SampleExpression,IEnumerator<string>,bool>> to Func<SampleExpression,bool>>


This is my class

class SampleExpression
{
    public string str;

    public static bool SampleEnum(SampleExpression s, IEnumerator<string> ien = null)
    {
        while (ien.MoveNext())
        {
            if (s.str == ien.Current)
            {
                ien.Reset();
                return true;
            }
        }
        return false;
    }
}

This is how i am generating my expression tree at runtime:

    static void Main(string[] args)
    {
        ParameterExpression param1 = Expression.Parameter(typeof(SampleExpression), "token");
        ParameterExpression param2 = Expression.Parameter(typeof(IEnumerator<string>), "args");

        var lstConstant = "1,2,3,4,".Split(new string[] { "," },
                           StringSplitOptions.RemoveEmptyEntries).ToList();

        var enummethod = typeof(SampleExpression).GetMethod("SampleEnum");
        MethodCallExpression methodCall = Expression.Call
                                        (
                                            enummethod,
                                            param1
                                            , param2
                                        );

        var e = Expression.Lambda<Func<SampleExpression, IEnumerator<string>, bool>>(methodCall, param1, param2);
        var l = e.Compile();

        List<SampleExpression> lst = new List<SampleExpression>();
        lst.Add(new SampleExpression { str = "1" }); // matches with lstConstant
        lst.Add(new SampleExpression { str = "2" }); // matches with lstConstant
        lst.Add(new SampleExpression { str = "5" });
        var items = lst.Where(x => l(x, lstConstant.GetEnumerator())).ToList();
    }

Now i might i have done this in a convoluted way(cause i am novice in Expression trees) - my requirement is this:

I have a comma separated string like this "1,2,3,4,". I want to split and match each SampleExpression with the string parameter str of the class SampleExpression. Which i have done so far.

However i want the Expression as Func<SampleExpression,bool>. As you can see currently its Func<SampleExpression, IEnumerator<string>, bool>.

How do i fix this.


Solution

  • The expression compilation seems weird to me too, but to actually answer your question...

    You can wrap the compiled Func like so:

    Func<SampleExpression, bool> lBind = (SampleExpression token) => l(token, lstConstant.GetEnumerator());
    

    This binds the enumerator as the second parameter, while leaving the first open for your input.