system.linq在gridview中对具有相同ID的行求和

时间:2014-06-29 07:43:33

标签: c# linq datagridview

我再次遇到同样问题,但这次是在gridview中对相同ID的行进行求和。我的gridview中有两列名为ID和quantity。议程是我必须手动输入ID和数量,我试图用相同的行ID来总结数量。一个例子是

ID数量
1234 1

1234 1

8976 2

8976 2

所以当我按下按钮时,ID 1234将有2个数量,8976将有4个数量。 我厌倦了在system.linq中使用group by函数,但是我的列和行变成了一个空单元格。有没有人有解决方案?任何帮助都应该非常感谢。

以下是我的代码段

我的主要表单类

int id = 0;
        int qty = 0;

        List<QuantityPerID> qtyList = new List<QuantityPerID>();



        foreach (DataGridViewRow row in dataGridView1.Rows)
        {

            if (null != row.Cells[0].Value)
            {
                id = int.Parse(row.Cells[0].Value.ToString());
            }
            if (null != row.Cells[1].Value)
            {
                qty = int.Parse(row.Cells[1].Value.ToString());
            }
            var sales = qtyList.Select(s => s.ID).Distinct().Select(order => new QuantityPerID
            {
                ID = order,
                Quantity= qtyList.Where(s => s.ID == order).Sum(s => s.Quantity),

            }).ToList();
            var source = new BindingSource();
            source.DataSource = qtyList;
            dataGridView1.DataSource = sales; 

我的quantityperID类代码

class QuantityPerID
{
    public int ID{ get; set; }
    public int Quantity { get; set; }
}

0 个答案:

没有答案
相关问题