在datagridview中计算类似单元格值的总和

在这个datagridview ,我想计算类似部门的总和。

也就是说,如果部门是第1行的架构,并且其下面的datagridview值的TMH单元格是36。

然后在第二行,我的部门设计,其TMH单元格值为45。

然后我再次选择了第三排的架构部门,其TMH值现在为45。

这是我的代码

  private void ProjectActivitiesGrid_CellEndEdit(object sender, DataGridViewCellEventArgs e) { Decimal sum = 0; #region THM CALCULATION. int column = ProjectActivitiesGrid.CurrentCell.ColumnIndex; string headerText = ProjectActivitiesGrid.Columns[column].HeaderText; DataGridViewRow d = this.ProjectActivitiesGrid.Rows[e.RowIndex]; String department = d.Cells[0].Value.ToString(); String chk = m_Project.projdepthrs.Where(c => c.DEPARTMENT == department).Select(c => c.DEPARTMENT).FirstOrDefault(); if (chk == null) { MessageBox.Show("Please fill up department alloted hrs first"); d.Cells[1].ReadOnly = true; d.Cells[2].ReadOnly = true; d.Cells[3].ReadOnly = true; d.Cells[4].ReadOnly = true; d.Cells[5].ReadOnly = true; d.Cells[6].ReadOnly = true; d.Cells[7].ReadOnly = true; } else { d.Cells[1].ReadOnly = false; d.Cells[2].ReadOnly = false; d.Cells[3].ReadOnly = false; d.Cells[4].ReadOnly = false; d.Cells[5].ReadOnly = false; d.Cells[6].ReadOnly = false; d.Cells[7].ReadOnly = false; String tmh = m_Project.projdepthrs.Where(c => c.DEPARTMENT == department).Select(c => c.TMH).First(); LBLAllotedhrs.Text = tmh; LBLLefthrs.Text = tmh; } foreach (DataGridViewRow rw in ProjectActivitiesGrid.Rows) { if (department == d.Cells[0].Value.ToString()) sum = sum + Convert.ToInt32(d.Cells[5].Value); else sum = 0; } LBLLefthrs.Text = (Convert.ToInt32(LBLLefthrs.Text) - Convert.ToInt32(sum)).ToString(); #endregion } 

然后,如果我得到我的总和为36 + 45的第1和第3行有类似的部门下拉列表。

我想要这种情况的逻辑。

所以如果我理解正确,你需要这样的东西:

 var result = m_Project.projdepthrs.Where(md=> md.DEPARTMENT == department) .Sum(ms=> Convert.ToInt32(ms.TMH)); 

如果我误解了,请评论。