Remove duplicates from datatable in C#


based on this

I create my data and I store them in a datatable.

Now I have another datatable which I fill it from my database.

I need to remove the duplicates from the first datatable and fill a datagridview.

This is what I have so far

 var rows = cols1.AsEnumerable()
                          .Where(r1 =>
                         .Any(r2 =>
                       var c1 = r1.Field<string>(0);
                       var c2 = r2.Field<string>(0);

                       var splitC1 = c1.Split(',').Select(x => x.Trim()).ToList();
                       var splitC2 = c2.Split(',').Select(x => x.Trim()).ToList();

                       return true

                             && (splitC1.Count() == splitC2.Count())

                              && !splitC1.Except(splitC2).Any();


        dgvfcolumns.DataSource = rows;

but it doesn't work. It displays the duplicate values, it doesn't remove them. How can I remove the duplicates and display only unique values in C# Datatable.

thank you

Asked by:- mspace
: 55 At:- 1/15/2019 1:22:34 PM
C# remove-duplicates-from-datatable

1 Answers
profileImage Answered by:- vikas_jk

Try using this C# Code 

var dtData3 = dtData2.AsEnumerable().Except(dtData1.AsEnumerable(), DataRowComparer.Default);

OR you can use the function below to get unique datatable value using C#

public DataTable CompareTwoDataTable(DataTable dtOriginalTable, DataTable dtNewTable, ArrayList columnNames)
        DataTable filterTable = new DataTable();
        filterTable = dtNewTable.Copy();
        string filterCriterial;
        if (columnNames.Count > 0)
            for (int iNewTableRowCount = 0; iNewTableRowCount < dtNewTable.Rows.Count; iNewTableRowCount++)
                filterCriterial = string.Empty;
                foreach (string colName in columnNames.ToArray())
                    filterCriterial += colName.ToString() + "='" + dtNewTable.Rows[iNewTableRowCount][colName].ToString() + "' AND ";
                filterCriterial = filterCriterial.TrimEnd((" AND ").ToCharArray());
                DataRow[] dr = dtOriginalTable.Select(filterCriterial);
                if (dr.Length > 0)
        return filterTable;

It should work.

At:- 1/17/2019 8:56:26 AM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly