0

Is there a way or a library in .NET to make something similar as Excel makes?

For example: I'd have an object Invoice with following members int Year int Number string Customer

and a "formula" in a string - for example "right(string(Year), 2) + \"/\" + string(Number, \"000000\""

and I'd like to generate a string dynamically from an object and the "formula" string (similar to Excel, but ofcourse without Excel)

Similar like NCalc is for math expressions mostly, but more specialized in string formulas...

Gomiunik
  • 410
  • 4
  • 11
  • *Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow* – I4V Sep 19 '13 at 20:01
  • Check out http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx – MetaGuru Sep 19 '13 at 20:52
  • "c# parsing formula in string" "is there a way"... sounds like an algorithmic question about how to parse a string of the form "func(param1,param2,nestedfunc(param1))". How would providing an example implementation library hurt the question or answer? Plus one. – Triynko May 17 '17 at 17:17

3 Answers3

0

I did something like this while ago. I just compile expression runtime. For tutorial you can look here: A Walkthrough of Dynamically Compiling C# code

Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116
  • How does it help for *`"right(string(Year), 2) + \"/\" + string(Number, \"000000\""`* ? – I4V Sep 19 '13 at 20:27
0

It is not as difficult as you might think to write a very simple interpreter for this sort of thing, especially if you keep the formulas in the style of FunctionName(Parameter, Parameter2 ...). I once did something similar within a day. You could perhaps use a function called CONCATENATE (à la Excel) instead of the + operator to keep it simple.

One approach would be to write a simple language object model with a class for each function you want to support, e.g.:

public abstract class ScriptFunction
{
     public abstract string Name { get; }
     public abstract int ParameterCount { get; }
     public abstract object Execute(params object[] parameters);
}

...then write a recursive Eval function that examines the provided script string, extracts the name and parameters of the function using the brackets as delimiters, looks up which ScriptFunction to call and then calls Execute on it.

The advantage of this approach over dynamic compilation is that you know that the code will only ever be able to do the things you have programmed it to do, whereas with something that compiled the expression to C# code you would have to be careful that the user did not input something catastrophic to the rest of the application.

For a more advanced approach see Regex for matching Functions and Capturing their Arguments

Community
  • 1
  • 1
Stephen Hewlett
  • 2,415
  • 1
  • 18
  • 31
-1

You could probably do this with an Aspect-Oriented plugin such as Post Sharp which basically allows run time code execution.

Coltech
  • 1,670
  • 3
  • 16
  • 31