对 datagridview 中一列的不同值求和

sum distinct values from a column in datagridview

我有一个包含两列的数据网格视图:

 group | quantity
------------------------
   chest  |  3
   legs   |  7
   back   |  2
   chest  |  1
   back   |  5
   legs   |  2

我想做的是将不同组的总和添加到一个列表中,并使用该列表填充另一个数据网格视图。

所以这个例子中的结果一定是:

   chest  |  4
   legs   |  9
   back   |  7
   

我尝试了一些 linq 查询代码,但没有成功。

我该怎么做?

这是我尝试过的一些 Linq 查询:

List<string> vv = dataGridView1.Rows.Cast<DataGridViewRow>()
    .Where(x => !x.IsNewRow)
    // either..
    .Where(x => x.Cells[7].Value != null)
    //..or or both
    .Select(x => x.Cells[7].Value.ToString())
    .Distinct()
    .ToList();

dataGridView6.DataSource = vv; 

编辑

组列在选择另一个列组合框后自动填充,数量是手动填充的。对于 group by 我找到了这段代码并且有效但如果单元格为空则抛出错误:

    var Sums = dataGridView1.Rows.Cast<DataGridViewRow>()
                  .GroupBy(row => row.Cells[7].Value.ToString()) // group column
                  .Select(g => new { User = g.Key, Sum = g.Sum(row => Convert.ToInt32(row.Cells[1].Value)) });
dataGridView6.DataSource = Sums.ToList(); 

好的,这是有效的解决方案:

var Sums = dataGridView1.Rows.Cast<DataGridViewRow>()
          .Where(row => row.Cells[7].Value != null)
        .GroupBy(row => row.Cells[7].Value.ToString()) // group column
        .Select(g => new { User = g.Key, Sum = g.Sum(row => Convert.ToInt32(row.Cells[1].Value)) }); // quantity column

        dataGridView6.DataSource = Sums.ToList();