IterateParameters without an IEnumerable

Topics: General, Help
Apr 9, 2012 at 9:26 PM

As mentioned before, we are building a calculation unit that has the formulas stored externally, so ALL evaluation is done with EvaluateOptions.IterateParameters, since almost all the time, they will be using atleast 1 dataset.  If you use EvaluateOptions.IterateParameters, e.Evaluate() will NOT return a result unless you have atleast one parameter set as an IEnumerable.

So, this works (from the unit tests):

            var e = new Expression("x * x", EvaluateOptions.IterateParameters);
            e.Parameters["x"] = new [] { 0, 1, 2, 3, 4 };

            var result = (IList)e.Evaluate();

            Assert.AreEqual(0, result[0]);
            Assert.AreEqual(1, result[1]);
            Assert.AreEqual(4, result[2]);
            Assert.AreEqual(9, result[3]);
            Assert.AreEqual(16, result[4]);

And this works:

            var e = new Expression("x + y", EvaluateOptions.IterateParameters);
            e.Parameters["x"] = new[] { 0, 1, 2, 3, 4 };
            e.Parameters["y"] = 2;

            var result = (IList)e.Evaluate();

            Assert.AreEqual(2, result[0]);
            Assert.AreEqual(3, result[1]);
            Assert.AreEqual(4, result[2]);
            Assert.AreEqual(5, result[3]);
            Assert.AreEqual(6, result[4]);

and this works:

            var e = new Expression("y", EvaluateOptions.IterateParameters);
            e.Parameters["y"] = new[] { 2 };

            var result = (IList)e.Evaluate();

            Assert.AreEqual(2, result[0]);

But this doesn't (as you would expect, and this is specifically trapped for and throws the "When IterateParameters option is used, IEnumerable parameters must have the same number of items" exception):

            var e = new Expression("x + y", EvaluateOptions.IterateParameters);
            e.Parameters["x"] = new[] { 0, 1, 2, 3, 4 };
            e.Parameters["y"] = new[] { 2 };

            var result = (IList)e.Evaluate();

            Assert.AreEqual(2, result[0]);
            Assert.AreEqual(3, result[1]);
            Assert.AreEqual(4, result[2]);
            Assert.AreEqual(5, result[3]);
            Assert.AreEqual(6, result[4]);

And unfortunately this also does NOT work, and does NOT throw an exception (well, actually accessing the result throws one, but NCalc does not).  It simply returns a blank dataset:

            var e = new Expression("y", EvaluateOptions.IterateParameters);
            e.Parameters["y"] = 2;

            var result = (IList)e.Evaluate();

            Assert.AreEqual(2, result[0]);

 What would be nice, is if the Expression.Evaluate() method would still return the value 2, either as an IEnumerable (length 1) or a single value.