[英]How to find sum of columns in datatable in c#
我正在使用以下代碼,但沒有得到任何結果,而是一片空白,並拋出諸如
Object cannot be cast from DBNull to other types.
第三和第四列是FF
和BW
數據表的值會像
C1 c2 FF BW
56 122 3 4
23 45 7
45 78 6
12 34 6 9
我想將總FF設為15,將總BW設為20
decimal FF = 0, BW = 0, AF = 0;
DataTable table = dtPointLinks.Clone();
table.Columns[0].DataType = typeof(string);
table.Columns[1].DataType = typeof(string);
table.Columns[2].DataType = typeof(string);
table.Columns[3].DataType = typeof(string);
// Declare an object variable.
object objFF;
objFF = table.Compute("Sum(FF)", string.Empty);
object objBW;
objBW = table.Compute("Sum(BW)", string.Empty);
FF = Convert.ToDecimal(objFF);
BW = Convert.ToDecimal(objBW);
不知道這里出了什么問題
在您的情況下,您可以嘗試傳統上的for循環以獲得所需的答案。
下面的示例代碼顯示了如何實現此目的。
decimal FF = 0;
decimal BW = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
if(dt.Rows[i]["FF"].ToString() != "")
{
FF += Convert.ToDecimal(dt.Rows[i]["FF"].ToString());
}
if (dt.Rows[i]["BW"].ToString() != "")
{
BW += Convert.ToDecimal(dt.Rows[i]["BW"].ToString());
}
}
最終結果將是FF = 15和BW = 20 。
希望這可以幫到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.