score:39

Accepted answer

simplifying, here are several lines which you are trying to do (i use string instead product etc, but idea is the same):

        expression<func<string, bool>> c1 = x => x.contains("111");
        expression<func<string, bool>> c2 = y => y.contains("222");
        var sum = expression.andalso(c1.body, c2.body);
        var sumexpr = expression.lambda(sum, c1.parameters);
        sumexpr.compile(); // exception here

please notice how i expanded your foreach into two expressions with x and y - this is exactly how it looks like for compiler, that are different parameters.

in other words, you are trying to do something like this:

x => x.contains("...") && y.contains("...");

and compiler wondering what is that 'y' variable??

to fix it, we need to use exactly the same parameter (not just name, but also reference) for all expressions. we can fix this simplified code like this:

        expression<func<string, bool>> c1 = x => x.contains("111");
        expression<func<string, bool>> c2 = y => y.contains("222");
        var sum = expression.andalso(c1.body, expression.invoke(c2, c1.parameters[0])); // here is the magic
        var sumexpr = expression.lambda(sum, c1.parameters);
        sumexpr.compile(); //ok

so, fixing you original code would be like:

internal static class program
{
    public class product
    {
        public string name;
    }

    private static void main(string[] args)
    {
        var searchstrings = new[] { "111", "222" };
        var cachedproductlist = new list<product>
        {
            new product{name = "111 should not match"},
            new product{name = "222 should not match"},
            new product{name = "111 222 should match"},
        };

        var filterexpressions = new list<expression<func<product, bool>>>();
        foreach (string searchstring in searchstrings)
        {
            expression<func<product, bool>> containsexpression = x => x.name.contains(searchstring); // not good
            filterexpressions.add(containsexpression);
        }

        var filters = combinepredicates<product>(filterexpressions, expression.andalso);

        var query = cachedproductlist.asqueryable().where(filters);

        var list = query.take(10).tolist();
        foreach (var product in list)
        {
            console.writeline(product.name);
        }
    }

    public static expression<func<t, bool>> combinepredicates<t>(ilist<expression<func<t, bool>>> predicateexpressions, func<expression, expression, binaryexpression> logicalfunction)
    {
        expression<func<t, bool>> filter = null;

        if (predicateexpressions.count > 0)
        {
            var firstpredicate = predicateexpressions[0];
            expression body = firstpredicate.body;
            for (int i = 1; i < predicateexpressions.count; i++)
            {
                body = logicalfunction(body, expression.invoke(predicateexpressions[i], firstpredicate.parameters));
            }
            filter = expression.lambda<func<t, bool>>(body, firstpredicate.parameters);
        }

        return filter;
    }
}

but notice the output:

222 should not match
111 222 should match

not something you may expect.. this is result of using searchstring in foreach, which should be rewritten in the following way:

        ...
        foreach (string searchstring in searchstrings)
        {
            var name = searchstring;
            expression<func<product, bool>> containsexpression = x => x.name.contains(name);
            filterexpressions.add(containsexpression);
        }
        ...

and here is output:

111 222 should match

score:1

imho, no need to make the list:

var filterexpressions = new list<expression<func<product, bool>>>()

you may easily live with the following in visitor class:

public class filterconverter : ifilterconvertervisitor<filter> {

    private lambdaexpression conditionclausepredicate { get; set; }
    private parameterexpression parameter { get; set; }

    public void visit(filter filter) {

        if (filter == null) {
            return;
        }

        if (this.parameter == null) {
            this.parameter = expression.parameter(filter.basetype, "x");
        }

        conditionclausepredicate = and(filter);
    }

    public delegate getconditionclause() {

        if (conditionclausepredicate != null) {

            return conditionclausepredicate.compile();
        }

        return null;
    }

    private lambdaexpression and(filter filter) {

        if (filter.basetype == null || string.isnullorwhitespace(filter.flattenpropertyname)) {

            //something is wrong, passing by current filter
            return conditionclausepredicate;
        }

        var conditiontype = filter.getcondition();
        var propertyexpression = filter.basetype.getflattenpropertyexpression(filter.flattenpropertyname, this.parameter);

        switch (conditiontype) {

            case filtercondition.equal: {

                var matchvalue = typedescriptor.getconverter(propertyexpression.returntype).convertfromstring(filter.match);
                var propertyvalue = expression.constant(matchvalue, propertyexpression.returntype);
                var equalexpression = expression.equal(propertyexpression.body, propertyvalue);
                if (conditionclausepredicate == null) {
                    conditionclausepredicate = expression.lambda(equalexpression, this.parameter);
                } else {
                    conditionclausepredicate = expression.lambda(expression.and(conditionclausepredicate.body, equalexpression), this.parameter);
                }
                break;
            }
        // and so on...
    }
}

the code is not optimal, i know, i'm a beginner and a lot of everything to be implemented... but this stuff does work. the idea is to have the only parameterexpression per visitor class, then to construct expressions using this parameter. after, just concatenate all expressions per one lambdaexpression clause and compile to delegate, when needed.


Related Query

More Query from same tag