[英]sum distinct values from a column in datagridview
I have a datagridview with two columns like this:我有一个带有两列的数据网格视图,如下所示:
group | quantity
------------------------
chest | 3
legs | 7
back | 2
chest | 1
back | 5
legs | 2
What I'm trying to do is to get the sum of distinct group to a list and use that list for populate another datagridview.我想要做的是将不同组的总和添加到列表中,并使用该列表填充另一个数据网格视图。
So the result must be in this example:所以结果一定是在这个例子中:
chest | 4
legs | 9
back | 7
I've tried some linq query code but without any success.我尝试了一些 linq 查询代码,但没有任何成功。
How can I do it?我该怎么做?
Here's some Linq queries I tried:这是我尝试过的一些 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;
EDIT编辑
the group column is being auto filled after a selection of another column combobox, the quantity is filled manually.选择另一个列组合框后,组列会自动填充,数量是手动填充的。 For the group by I found this code and works but throw an error if a cell is empty:对于 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();
ok, here the solution that works:好的,这里是有效的解决方案:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.