Simple Calculations With .NET

The idea for this post came from a recent post of Salvador Gascon (@salvadorgascon): http://salvadorgascon.wordpress.com/2014/09/27/how-evaluate-math-expressions/.

For simple math expressions calculation I use the DataTable class. Very simple and we already have it! Also, we can use some SQL expressions (list at http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx):

   1: var table = new DataTable();
   2: table.Columns.Add("A", typeof(int));
   3: table.Columns.Add("B", typeof(int));
   4:  
   5: var c = new DataColumn("C"){ Expression = "[A] + [B]" };
   6: table.Columns.Add(c);
   7:  
   8: var d = new DataColumn("D"){ Expression = "ISNULL([A], [B])" };
   9: table.Columns.Add(d);
  10:  
  11: table.Rows.Add(1, 2);
  12:  
  13: var resultc = table.Rows[0]["C"];    //3
  14: var resultd = table.Rows[0]["D"];    //1

It can also be used for aggregations:

   1: var sum = table.Compute("SUM([A])", String.Empty);
   2: var avg = table.Compute("AVG([B])", String.Empty);

For the list of supported expressions, see http://msdn.microsoft.com/en-us/library/system.data.datatable.compute.aspx.

Easy, and no need for external libraries! Winking smile

                             

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website