[英]sum multiple digits if cell contains some symbols
我有一个 datagridview,我正在计算一列中的值并乘以另一个列值,然后对所有行进行求和,并使用以下代码在标签中显示结果:
int sum2 = 0;
for (int m = 0; m < dataGridView1.Rows.Count; ++m)
{
sum2 += getCellRepsSum(dataGridView1.Rows[m]);
}
label18.Text = sum2.ToString();
int getCellRepsSum(DataGridViewRow dr)
{
int serie = Convert.ToInt32(dr.Cells[1].Value);
int l = Convert.ToInt32(dr.Cells[2].Value); //reps
int result = 0;
result = serie * l;
return result;
}
如果我设置了一个数字,这可以正常工作,但是我想根据 + 或 - 等符号的存在添加一个条件。
所以就像......如果“ripetizioni”列的单元格值包含“-”或“+”,那么对每个符号之间的数字求和,然后像我的代码一样相乘。
示例:12-8-6 需要对 12 + 8 + 6 求和,然后乘以“serie”列,如我的代码等。
我试过这样但不起作用,因为“-”符号不允许 ToInt 转换:
int sum2 = 0;
for (int m = 0; m < dataGridView1.Rows.Count; ++m)
{
sum2 += getCellRepsSum(dataGridView1.Rows[m]);
}
label18.Text = sum2.ToString();
int getCellRepsSum(DataGridViewRow dr)
{
int serie = Convert.ToInt32(dr.Cells[1].Value);
int result = 0;
string l = Convert.ToString(dr.Cells[2].Value);
if (l.Contains("-")) {
int lt = Convert.ToInt32(dr.Cells[2].Value);
int sumReps = 0;
while (lt > 0)
{
sumReps += (lt % 10);
lt = lt / 10;
}
result = sumReps;
return result;
}
else {
//reps
int li = Convert.ToInt32(dr.Cells[2].Value); //reps
result = serie * li;
return result;
}
return result;
}
我该如何解决这个问题?
改变
int lt = Convert.ToInt32(dr.Cells[2].Value);
至
int lt = dr.Cells[2].Value.ToString().Split('+','-').Select(int.Parse).Sum();
别忘了乘以serie
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.