Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying columns in a datatable

Tags:

c#

datatable

I have a datatable in C# with a "price" column and an "allocation" column, and I need to multiply the price column by the allocation column and put the result in the price column. Is there a way to do with without looping over the table? I have tried something like this:

DataTable dt = getData();
dt.Columns["Price"].Expression = "Allocation * Price";

But obviously this gives me the following exception:

Cannot set Expression property due to circular reference in the expression.

Does anyone know of another way to accomplish this? Thanks beforehand.

like image 812
SuperTron Avatar asked Nov 16 '11 17:11

SuperTron


3 Answers

You could use a LINQ expression to do it in one line:

dt.Rows.ForEach(x => x["Price"] = (double)x["Price"] * (double)x["Allocation"]);
like image 129
Dylan Smith Avatar answered Oct 04 '22 17:10

Dylan Smith


You could just add another column to the DataTable:

dt.Columns.Add("TotalPrice", typeof(decimal));
dt["TotalPrice"] = "Allocation * Price";
like image 38
James Johnson Avatar answered Oct 04 '22 18:10

James Johnson


Add a new column whose value is calculated from the other two:

dt.Columns.Add("TotalPrice", typeof(decimal), "Allocation * Price");

With this approach, the TotalPrice will always be up to date if you change the Price or Allocation

like image 36
Thomas Levesque Avatar answered Oct 04 '22 17:10

Thomas Levesque