Created
November 11, 2016 18:50
-
-
Save eabreusantos/340b58aa4a16456bfc847c56724ca14d to your computer and use it in GitHub Desktop.
Formula com calculo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Text.RegularExpressions; | |
using System.Data; | |
namespace ConsoleApplicationteste | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine("Olá"); | |
//Exemplo de uso | |
Formula formula = new Formula("(#(AB)+#(CD))-#(DD)"); | |
Dictionary<string,decimal> examples = new Dictionary<string, decimal> {}; | |
examples.Add("AB", 10); | |
examples.Add("CD", 20); | |
examples.Add("DD", 10); | |
object result = formula.calculate(examples); | |
Console.WriteLine("O resultado da expressao (#(AB)+#(CD))-#(DD) e = " + result); | |
Console.ReadKey(); | |
} | |
} | |
class Formula | |
{ | |
string formula; | |
string pattern = @"(?<=\#\().*?(?=\))"; | |
public Formula(string formula) | |
{ | |
this.formula = formula; | |
} | |
public List<string> GetCodes() | |
{ | |
MatchCollection matchList = Regex.Matches(this.formula, this.pattern); | |
var codes = matchList.Cast<Match>().Select(match => match.Value).ToList(); | |
return codes; | |
} | |
public object calculate(Dictionary<string,decimal> codeValues) | |
{ | |
string expression = this.formula; | |
//Transforma formula para expressao | |
foreach (var current in codeValues) | |
{ | |
string tag = "#(" + current.Key.ToString() + ")"; | |
expression = expression.Replace(tag, current.Value.ToString()); | |
} | |
//Calcula formula | |
object result = new DataTable().Compute(expression,""); | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment