在windows c#中获取数据gridview列中相同值的计数 [英] get count of identical values in column of data gridview in windows c#

查看:275
本文介绍了在windows c#中获取数据gridview列中相同值的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个datagridview,其中包含一个包含一些相同值的列,如下所示,列A包含相同的值。我希望得到相同值的数量。



例如: -

AB

ppp abc

abc hij

ppp def

我试过这个但不行。

I have a datagridview which contains a column containing some identical values as shown below column A contains identical values. i want to get the count of identical values in it.

For ex:-
A B
ppp abc
abc hij
ppp def
I have tried this but not working.

arrListIDs = new System.Collections.ArrayList();
           for (int k = 0; k < GrdItDetail.Rows.Count; k++)
           {
               string stritemcode = GrdItDetail.Rows[k].Cells["ItemCode"].Value.ToString();
               if (!arrListIDs.Contains(stritemcode))
               {
                   arrListIDs.Add(stritemcode);
                   //do ur code
               }
               else
               {
                   if (arrListIDs[0].ToString() == stritemcode)
                       arrListIDs.Add(stritemcode);
               }
           }



任何想法。任何建议。

请帮助。

在此先感谢。


Any ideas .Any suggestions.
Please Helpme.
Thanks in advance.

推荐答案

当您学习如何使用Linq时,这种任务变得非常简单,但是,让我们看看如何使用词典来完成它:
When you learn how to use Linq, this kind of task becomes very easy, but, let's see how you can do it using a Dictionary:
public Dictionary<string,> StrToNDuplicates = new Dictionary<string,>();

public void GetColumnDuplicates(string colName)
{
    StrToNDuplicates.Clear();

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        string val = row.Cells[colName].Value.ToString();

        if (! StrToNDuplicates.ContainsKey(val))
        {
           StrToNDuplicates.Add(val,0);
        }

        StrToNDuplicates[val]++;
    }
}

// for testing:
private void printDict()
{
    foreach (var kvp in StrToNDuplicates)
    {
        Console.WriteLine("Value: {0} NDuplicates: {1}", kvp.Key, kvp.Value);
    }
}

这会迭代行,获取每行内指定列的单元格值。然后,如果字典中还没有'具有当前值的键,则创建一个'键,其值初始化为#0。



每个值都会导致字典的count字段的增量。因此,当您从调用此函数返回时,'StrToNDuplicates Dictionary将为每个不同的值包含一个条目('Key),以及相应的'Value,即该不同字符串值的重复数。

This iterates over the rows, getting the value of the cell at the named column within each row. Then, if the Dictionary doesn't already have a 'Key with the current value, a 'Key is created, its Value initialized to #0.

Each value causes an increment of the count field of the Dictionary. So, when you return from calling this function, the 'StrToNDuplicates Dictionary will contain one entry ('Key) for each distinct value, and a corresponding 'Value which is the number of duplicates of that distinct string value.


这篇关于在windows c#中获取数据gridview列中相同值的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆