简体   繁体   English

如何在C#中基于DataGridView中的另一列对行进行计数

[英]How to Count the rows based on another Column in a DataGridView in C#

I have 7 columns in these three are ReadOnly Fields and based on Consumable Name i want to Sum the Quantity Issued Field. 我在这三个字段中有7列是“只读”字段,并且基于“消耗品名称”,我想对“已发出数量”字段求和。

i want to Sum the Quantity Issued based on the Consumable Name and the total sum is compared to the Quantity Required They are so many consumable Names. 我想对基于消耗品名称的已发行数量求和, 并将总和与所需数量进行比较。它们是如此之多。 My question How to calculate the Quantity Issued Column based on Consumable Name . 我的问题是如何根据消耗品名称计算数量列。 I tried and finally i got the answer it is something logically i am failed to explain it. 我尝试了一下,最后我得到了答案,这在逻辑上是我无法解释的。

1)Create a List of strings with all rows of column 'Consumable Name'. 1)创建一个字符串列表,其中包含“消耗品名称”列的所有行。 Fill with names. 填写姓名。

2)Create a List of integers equal to the number of items in the above List. 2)创建一个整数列表,该整数等于上述列表中的项目数。 Fill with quantities. 充满数量。

3)Create a List of distinct strings from (1). 3)从(1)创建一个不同字符串列表。

4)Create a List of integers equal to the number of items in (3). 4)创建一个等于(3)中项数的整数列表。

5)Step into each distinct element and get the related matching 'Consumable Name' and add quantities. 5)进入每个不同的元素,并获得相关的匹配“消耗品名称”并添加数量。

6)Similar steps you can follow if you wish to compare or check other columns. 6)如果您想比较或检查其他列,可以遵循类似的步骤。

You can refer to the below code: 您可以参考以下代码:

    public void getQuantity()
    {
        List<string> consumbleNames = new List<string>();
        List<int> quantity = new List<int>();

        //Cells[5] refer to 6th column : Quantity issued: you can use column name too
        for (int i = 0; i < yourDataGridView.Rows.Count; i++)
        {
            consumbleNames.Add(yourDataGridView.Rows[i].Cells[0].Value.ToString());
            quantity.Add((int)Convert.ToInt32(yourDataGridView.Rows[i].Cells[5].Value.ToString()));
        }

        List<string> distinctNames = new List<string>(consumbleNames.Distinct());
        List<int> quantityRelated = new List<int>(distinctNames.Count);

        for (int i = 0; i < distinctNames.Count; i++)
        {
            quantityRelated.Add(new int());

            for (int j = 0; j < consumbleNames.Count; j++)
            {
                if (consumbleNames[j].Equals(distinctNames[i]))
                {
                    quantityRelated[i] += quantity[j];
                }
            }
        }

        foreach (int t in quantityRelated)
        {
            /* quantity corresponds to the each distinct item */
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM