1

I am working on one project that will utilize nCalc to work with some calculation. These calculation will also contain some function.g.: sum(), avg() etc. Very much like Excel function: sum() will summarize all of the numbers that are provided in brackets and avg will do average.

I have started implementing some changes but I am not even sure if I started in a correct place. But if I started in correct place then what I need to do is to access the parameters so that I can iterate and summarize them.

Up until now I have created a new case in EvaluationVisitor.cs like so:

case "sum":
                CheckCase("sum", function.Identifier.Name);


                if (function.Expressions.Length != 3) { 
                    throw new ArgumentException("sum() takes exactly 3 arguments");
                }

                string sum = "";

                for (int i = 1; i < function.Expressions.Length; i++)
                {

                    //here comes the logic for getting all parameters and summing them.
                    //one thing I am not sure about is how to access input parameters 
                    sum = ...;

                }

                Result = sum;

                break;

I am very new to both C# and nCalc, and some help would be greatly appreciated.

Thanks in advance!

marpik
  • 56
  • 7

1 Answers1

2

Please give this a try. Add this code to new switch case ("sum") in EvaluationVisitor.cs :

case "sum" :
    CheckCase("Sum", function.Identifier.Name);

                        object[] inputs = new object[function.Expressions.Length];
                        for (var i = 0; i < function.Expressions.Length; i++)
                        {
                            inputs[i] = Evaluate(function.Expressions[i]);
                        }

                        Result = Numbers.Sum(inputs);
break;

New method in Numbers.cs file :

public static object Sum(params object[] inputs)
        {
            var sum = inputs[0];
            for (int i = 1; i < inputs.Length; i++)
            {
                sum = Add(sum,inputs[i]);
            }

            return sum;
        }
Anuj Shukla
  • 271
  • 3
  • 7
  • Hi Anju, Thanks for you answer. I actually figured it out with very similar solution;) Debugging already implemented functions helped me a lot. Thanks again! Marcin – marpik Feb 02 '15 at 09:16
  • I wonder how many people have implemented Sum in nCalc! Anyway, if this answer answered your question consider marking it as accepted so others may be helped! – RyanfaeScotland Feb 04 '15 at 15:39