2

I am working on a C# project and let's assume I have a string containing something like this:

string content = "[IF FullName = 'Bob Smith']Hello my friend";
content += "[ELSEIF TotalPurchases > 1000]Dear valued customer";
content += "[ELSE]Dear [FirstName]";
content += "[ENDIF]";

and let's assume I have a Key/Value dictionary where keys are "FullName" and "TotalPurchases" and values are "Jane Doe" and "500". What would be a good way to parse the content and most importantly evaluate the "IF...ELSE...ENDIF"?

Is there an open source project I can leverage or should I just write my own code to parse the content?

desautelsj
  • 3,587
  • 4
  • 37
  • 55

2 Answers2

0

I'm a little confused. Is that really your string, or are you talking about the string that would be generated by that C# source code?

I'm assuming the latter and I'd probably just parse it myself since it's not overly complicated and somewhat specialized. There's also a text parser helper class I wrote that may help you out.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • The example in my question is a little bit simplified but it's pretty close to an acutal string. My goal is to be able to evaluate the "IF...ELSE...ENDIF" to produce the final content. For instance, if my data contains "Bob Smith", the resulting content would be "Hello my friend", if my data contains "Jane Doe" and Jane has spent more than $1,000, the resulting content would be "Dear valued customer", etc. Thanks for offering your helper class but I'm afraid it's too simplistic for my needs. – desautelsj Apr 27 '11 at 14:59
  • @desautelsj: That's fine if you don't use my class. But I thought I'd mention that I've used it to write a language interpretor. The class doesn't do that much, but I use it as a base class that makes the low-level parsing easier. – Jonathan Wood Apr 27 '11 at 15:04
  • sounds interresting... can you share your language interpretor? – desautelsj Apr 27 '11 at 15:21
  • I eventually plan to publish it on my [Black Belt Coder](http://www.blackbeltcoder.com) site, but it may be quite a while as I'm busy with other projects. (Although I am available for consulting. :) – Jonathan Wood Apr 27 '11 at 15:38
0

One option is to replace the 'If Else End If' textual data above with actual C# if statement logic and compile your dynamically built C# text at runtime to evaluate your if logic. The primary class to handle this dynamic C# compilation would be the CSharpCodeProvider Class

CsharpCodeProvider info http://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider.aspx

Matt
  • 1,168
  • 2
  • 15
  • 24