在数据表中乘列 [英] Multiplying columns in a datatable

查看:64
本文介绍了在数据表中乘列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中有一个数据表,其中包含价格列和分配列,我需要将价格列乘以分配列并将结果放入价格列。有没有一种方法可以不遍历表?我试过这样的事情:

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.

推荐答案

您可以使用LINQ表达式在一行中完成该操作:

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

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

这篇关于在数据表中乘列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆