Abohy
Abohy

Reputation: 35

How to count rows in datagridview and consider duplicate rows as single?

I have a datagridview that contains many rows, some of this rows have duplicate values.

This datagridview is addable .. I add and remove rows frequently.

I want to count rows every time i add row or remove it, and consider duplicate rows as a single.

I tried this code:

int total = 0;
        for (int currentRow = 0; currentRow < dataGrid_Target.Rows.Count - 1; currentRow++)
        {
            DataGridViewRow rowToCompare = dataGrid_Target.Rows[currentRow];

            for (int otherRow = currentRow + 1; otherRow < dataGrid_Target.Rows.Count; otherRow++)
            {
                DataGridViewRow row = dataGrid_Target.Rows[otherRow];
                if (!row.IsNewRow)
                {
                    if (!Convert.ToString(rowToCompare.Cells[0].Value).Equals(Convert.ToString(row.Cells[0].Value)))
                    {
                        total++;

                    }
                    else
                    {
                        total = total+1;
                    }
                }
            }
        }

But it doesn't help.

Upvotes: 1

Views: 993

Answers (2)

Tim Rutter
Tim Rutter

Reputation: 4679

Linq is your friend in this case:

return dataGrid_Target.Rows
    .Cast<DataGridViewRow>()
    .Select(r => Convert.ToString(r.Cells[0].Value))
    .Distinct()
    .Count();

i'll explain each bit:

Cast: You can't use linq on a DataGridViewRowCollection(Rows) as it doesn't implement IEnumerable<T> so you have to cast it like this (detailed explanation here)

Select: returns the first cell of each row as a string

Distinct: returns only the distinct entries i.e. remove duplicates

Count: counts the number of distinct entries.

Upvotes: 4

cKai
cKai

Reputation: 67

Your if-else clause does nothing. total++ and total = total + 1 are the same.

Since you only want to count the row, if it doesnt have a duplicate. You need to move your counter in the first for-loop.

    int total = 0;
    for (int currentRow = 0; currentRow < dataGrid_Target.Rows.Count - 1; currentRow++)
    {
        bool IsRowDuplicate = false;
        DataGridViewRow rowToCompare = dataGrid_Target.Rows[currentRow];

        for (int otherRow = currentRow + 1; otherRow < dataGrid_Target.Rows.Count; otherRow++)
        {
            DataGridViewRow row = dataGrid_Target.Rows[otherRow];
            if (!row.IsNewRow)
            {
                if (Convert.ToString(rowToCompare.Cells[0].Value).Equals(Convert.ToString(row.Cells[0].Value)))
                {
                    IsRowDuplicate = true;
                    break;
                }
            }
        }

        if(!IsRowDuplicate)
        {
           total++;
        }
    }

Upvotes: 1

Related Questions