Column multiplication in datatable

I have a datatable in C # with a price column and a distribution column, and I need to multiply the price column by the distribution column and put the result in the price column. Is there a way to do this without looping over the table? I 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 a different way of doing this? Thanks in advance.

+6
source share
4 answers

You can use the LINQ expression to do this on one line:

 dt.Rows.ForEach(x => x["Price"] = (double)x["Price"] * (double)x["Allocation"]); 
+4
source

You can simply add another column to the DataTable:

 dt.Columns.Add("TotalPrice", typeof(decimal)); dt["TotalPrice"] = "Allocation * Price"; 
+2
source

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

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

With this approach, TotalPrice will always be updated if you change Price or Allocation

+1
source

If you do not have a separate column, what happens when something forces you to perform the calculation again ....

At some point, the amount of code you need to add to bend the datatable to do what you want (without introducing the mass of potential erm capabilities) will be more effort than just knocking down a class to hold things.

Reading from a datatable write from a databale is not difficult and is not required for a list of things.

0
source

Source: https://habr.com/ru/post/901636/


All Articles