繁体   English   中英

将一列中的数字总和与另一列中的数字总和相乘? 访问C#

[英]Multiplying the sum of numbers in a column with the sum of numbers in another column? Access to C#

该程序在“数据网格视图”中显示数据库信息。 我需要将第1列中的所有数字相加,然后将第3列中的所有数字相加,然后将两个总和相乘。

此代码仅将最后一行的列1和列3相乘。 有什么建议么?

这是我第一次连接数据库,因此如果这看起来很愚蠢,我深表歉意。

                foreach (DataRow currentRow in itemDS.Tables[0].Rows)
                {
                    // add to data grid view
                    invoiceDataGridView.Rows.Add(currentRow[1].ToString(),   currentRow[2].ToString(), currentRow[3].ToString());

                    var itemQuant = Convert.ToDecimal(currentRow[1]);
                    var priceEach = Convert.ToDecimal(currentRow[3]);

                    decimal subTotal = itemQuant * priceEach;

                    subTotalOutput.Text = subTotal.ToString();
                }

您的意思是您不确定如何在循环结构中保持连续运行吗? 如果是这样的话:

decimal total = 0; //declare outside the foreach

foreach (DataRow currentRow in itemDS.Tables[0].Rows)
                {
                    // add to data grid view
                    invoiceDataGridView.Rows.Add(currentRow[1].ToString(),   currentRow[2].ToString(), currentRow[3].ToString());

                    var itemQuant = Convert.ToDecimal(currentRow[1]);
                    var priceEach = Convert.ToDecimal(currentRow[3]);

                    decimal subTotal = itemQuant * priceEach;

                    total += subTotal;
                }

//do something with total here, after for each finishes

您可以使用linq求和。

var sum = itemDS.Tables[0].AsEnumerable().Sum(dr => dr.Field<int>("value"));

"value"将是itemDS中数据表的列名。 您必须在此处指定列名。

像上面的语句一样取下一列的总和。 加乘..

希望这可以帮助.. :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM