Compare values of datatable and remove duplicate

Padmanabhan, Venkatesh 125 Reputation points
2023-04-14T12:02:23.64+00:00

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

Thanks

Developer technologies | C#
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2023-04-14T14:32:09.3333333+00:00

    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.Columns.Add("col1");
    dt.Columns.Add("col2");
    dt.Columns.Add("col3");
    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;
        }
        else
        {
            seenCol1Values.Add(col1Value);
        }
    }
    dataGridView1.DataSource = dt;
    

    enter image description here

    Best Regards,

    Jiale


    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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.