Geek Culture
Published in

Geek Culture

How To Calculate String Formulas At Runtime On .Net

NASA in 1961(Image credits: J. R. Eyerman, via LIFE)

CMIW*CCL*(FG+CG)/10⁶+1+sqrt(3)

This is our example Formula model:

public  class FormuleModel:IFormuleModel
{
public double CMIW { get; set; }
public int CCL { get; set; }
public int FG { get; set; }
public int CG { get; set; }
}
public interface IFormuleModel
{
public object this[string propertyName]
{
get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
}
}

Every formula which expresses a law of nature is a hymn of praise to God. — Maria Mitchell

Now we will create a string Extension static class. We will calculate string formulas with this extension.

return (decimal)expr.EvalNumerical();

CalculateFormulas.cs: Custom string Extension class.

public static decimal CalculateFormulas(this string formule, IFormuleModel model)
{
String pattern = @"([A-Z]|[a-z])+([A-z]|[a-z]|\d|_)*";
String output = String.Join(",",
Regex.Matches(formule, pattern)
.OfType<Match>()
.Where(item => item.Value != "sqrt")
.Select(item => item.Value));
int i = 0;
output.Split(',').ToList().ForEach(item =>
{
formule = formule.Replace(item, "{" + i.ToString() + "}");
i++;
});
var varableArray = output.Split(',');
Object[] prms = new Object[varableArray.Length];
var index = 0;
varableArray.ToList().ForEach(prm =>
{
prms[index] = model[prm];
index++;
});
formule = String.Format(formule, prms);
Entity expr = formule;
return (decimal)expr.EvalNumerical();
}
internal class Program
{
static void Main(string[] args)
{
String source = "CMIW*CCL*(FG+CG)/10^6+1+sqrt(3)";
FormuleModel model = new FormuleModel() { CMIW = 4.5, CCL = 1, FG = 4, CG = 3 };
var result = source.CalculateFormulas(model);
Console.WriteLine(result);
}
}

Success has a simple formula: Do your best, and people may like it. — Sam Ewing

Conclusion:

Goodbye

--

--

A new tech publication by Start it up (https://medium.com/swlh).

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Bora Kaşmer

I have been coding since 1993. I am computer and civil engineer. Microsoft MVP. Senior Software Architect. Ride motorcycle. Gamer. Have two daughters.