nreco / lambdaparser

Runtime parser for string expressions (formulas, method calls). Builds dynamic LINQ expression tree and compiles it to lambda delegate.
http://www.nrecosite.com/
MIT License
307 stars 55 forks source link

Lambda Sum or Select #33

Open BossJake opened 3 years ago

BossJake commented 3 years ago

Hey guys, I'm trying to perform the expression below like Sum(x=>x.UnitQuantity) or Select(x=>x...) but I'm unable to parse it properly and I am getting this exception error below. Am I missing something with my expression?

NReco.Linq.LambdaParserException: 'Expected value at 22: order.OrderLines.Sum(d => d.UnitPrice * d.UnitQuantity)'

`

       var lambdaParser = new LambdaParser();
        var order = new Order()
        {
            Id = 1,
            Paid = true,
            OrderReference = "Animal",
            OrderLines = new List<OrderLine>
                {
                    new OrderLine
                    {
                        Id = 1,
                        UnitQuantity = 3,
                        Category = "CAT",
                        UnitPrice = 1.1M
                    },
                    new OrderLine
                    {
                        Id = 2,
                        UnitQuantity = 7,
                        Category = "DOG",
                        UnitPrice = 3.1M
                    }
                }
        };

        var context = new Dictionary<string, object>
        {
            ["order"] = order
        };

        //var expression = "order.Paid ? order.OrderLines.Sum(d=>d.UnitPrice * d.UnitQuantity) : order.OrderLines.Sum(d=>d.UnitPrice * d.UnitQuantity) * 2.0M";

  var expression = "order.OrderLines.Sum(d => d.UnitPrice * d.UnitQuantity)";
       var result = lambdaParser.Eval(expr, context);

`

VitaliyMF commented 3 years ago

NReco.LambdaParser is about simple expressions (math operations, method calls, accessing properties/fields). It doesn't support delegates definition that "Sum" expects.

Also, "Sum" is an extension method for IEnumerable -- in other words, this is a static method -- and LambdaParser doesn't support static method calls. This is by design; usually expressions are composed by the app end-users and should be evaluated in a 'safe' way, and everything that can be used in the expression (variables, methods) should be passed with a context.

I'm not sure that this capability (delegates definition) can be added easily. In my projects where I use LambdaParser delegates are not needed, so if you need them you may develop this functionality by yourself. We can discuss the details if you want to contribute this with PR.