将数据表中的列相乘
我在C#中有一个带有“价格”列和“分配”列的数据表,我需要将price列乘以分配列,并将结果放在price列中。 有没有办法没有循环表? 我尝试过这样的事情:
DataTable dt = getData(); dt.Columns["Price"].Expression = "Allocation * Price";
但显然这给了我以下例外:
Cannot set Expression property due to circular reference in the expression.
有谁知道另一种方法来实现这一目标? 先谢谢。
您可以使用LINQ表达式在一行中执行此操作:
dt.Rows.ForEach(x => x["Price"] = (double)x["Price"] * (double)x["Allocation"]);
您可以向DataTable添加另一列:
dt.Columns.Add("TotalPrice", typeof(decimal)); dt["TotalPrice"] = "Allocation * Price";
添加一个新列,其值来自另外两个:
dt.Columns.Add("TotalPrice", typeof(decimal), "Allocation * Price");
使用此方法,如果您更改Price
或Allocation
, TotalPrice
将始终是最新的
如果你没有单独的列,那么当某些东西使计算再次执行时会发生什么….
在某些时候,您必须添加弯曲数据表以执行您想要的代码(不引入大量潜在的’ermfunction)将比仅仅敲取一个类来保存这些东西更省力。
从数据表中读取来自数据库的内容并不难,也不会绑定到一个东西列表。