Compare values of datatable and remove duplicate

Padmanabhan, Venkatesh 120 Reputation points

Hi. I have a data table with few columns. F some of the columns, I have some duplicate values.

col1 col2 col3
Region cell2 Cell 2
Region cell2 Cell 4
Green cell3 cell5
Green cell3 cell7

For example: I want to compare the col1 values and then keep the datatable as below. How to achieve this ?

col1 col2 col3
Region cell2 Cell 2
cell2 Cell 4
Green cell3 cell5
cell3 cell7


An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,369 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jiale Xue - MSFT 35,716 Reputation points Microsoft Vendor

    Hi @Padmanabhan, Venkatesh ,welcome to Microsoft Q&A.

    You could directly add a null value directly from the second line when creating it.

    You could create a HashSet<string>. Start traversing from the first row, if the current row value is not in it, keep it and save it in HashSet; if it exists, make it empty.

    The specific code is as follows:

    DataTable dt = new DataTable();
    dt.Rows.Add("Region", "Cell 2", "XXXX 3");
    dt.Rows.Add("Region", "Cell 5", "XXXX 4");
    dt.Rows.Add("Region", "Cell 6", "XXXX 7");
    dt.Rows.Add("Green", "cell5", "XXXX 8");
    dt.Rows.Add("Green", "cell7", "XXXX 9");
    HashSet<string> seenCol1Values = new HashSet<string>();
    for (int i = 0; i <= dt.Rows.Count - 1; i++)
        DataRow row = dt.Rows[i];
        string col1Value = row["col1"].ToString();
        if (seenCol1Values.Contains(col1Value))
            row["col1"] = DBNull.Value;
    dataGridView1.DataSource = dt;

    enter image description here

    Best Regards,


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments