Click here to Skip to main content
15,911,039 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
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.
C#
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.
Posted
Comments
BillWoodruff 1-Feb-16 8:58am    
Do you need to deal with the case where there is more than one "set" of duplicate values ? If you have this for the column:

abc
def
abc
abc
def

Do you need a result which tells you there are two groups of duplicate values, or, do you need a result that tells you there are a total of six items that are duplicates ?

1 solution

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:
C#
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);
    }
}
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900