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.
You could use a LINQ expression to do it in one line:
dt.Rows.ForEach(x => x["Price"] = (double)x["Price"] * (double)x["Allocation"]);
You could just add another column to the DataTable:
dt.Columns.Add("TotalPrice", typeof(decimal));
dt["TotalPrice"] = "Allocation * Price";
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With