evaluating expressions

  • Thread starter Thread starter jake
  • Start date Start date
J

jake

Is there a way to evaluate a string expression such as "55/8" to
return 6.875?
Your help is greatly appreciated.
jake
 
Is there a way to evaluate a string expression such as "55/8" to
return 6.875?
Your help is greatly appreciated.
jake

If you're on .NET 3.5, by far the easiest way is to use the Dynamic
LINQ sample. It would look something like this:

var expr = DynamicExpression.ParseLambda(null, typeof(decimal), "55 /
8");
var method = (Func<decimal>)expr.Compile();
Console.WriteLine(method()); // 6.875

You can find the download links to it here:

You can download it from here
 
Thank you Pavel,
Yes I am using 3.5 and I am very familiar with LINQ and lambda
expressions. I just didn't know about this particular one. This is
exactly what I need.
Thanks again.
What would we do without these forums!!
jake
 
If you're on .NET 3.5, by far the easiest way is to use the Dynamic
LINQ sample. It would look something like this:

var expr = DynamicExpression.ParseLambda(null, typeof(decimal), "55 /
8");
var method = (Func<decimal>)expr.Compile();
Console.WriteLine(method()); // 6.875

You can find the download links to it here:

Mis-pasted the link, so here it is:

http://weblogs.asp.net/scottgu/arch...t-1-using-the-linq-dynamic-query-library.aspx

Note that this is not a part of .NET 3.5 by itself - rather, it is a
"code sample" that runs on 3.5
 
jake said:
Is there a way to evaluate a string expression such as "55/8" to
return 6.875?

You can use the JavaScript support in .NET - the code below
will work on at least 2.0 (and you can write similar code
for 1.1) unlike the dynamic LINQ solution.

Arne

==================================================

using System;
using System.Reflection;
using System.CodeDom.Compiler;

using Microsoft.CSharp;
using Microsoft.JScript;

namespace E
{
public interface IJS
{
double Eval(string expr);
}
public class JS
{
private static IJS engine;
static JS()
{
string src = "import System; import E; public class C
implements IJS { public function Eval(expr : String) : Double { return
eval(expr); } }";
CodeDomProvider comp = new JScriptCodeProvider();
CompilerParameters param = new CompilerParameters();
param.GenerateInMemory = true;
param.ReferencedAssemblies.Add("System.dll");

param.ReferencedAssemblies.Add(System.Reflection.Assembly.GetExecutingAssembly().Location);
CompilerResults res = comp.CompileAssemblyFromSource(param,
src);
Assembly asm = res.CompiledAssembly;
engine = (IJS)asm.CreateInstance("C");
}
public static double Eval(string expr)
{
return engine.Eval(expr);
}
}
}
 
Back
Top