Remove duplicates from datatable in C#


Hello

based on this

https://www.technical-recipes.com/2017/obtaining-combinations-of-k-elements-from-n-in-c/#comment-52343

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 =>
                         cols2
                            .AsEnumerable()
                         .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();



                   }
                )
        ).CopyToDataTable();

                
        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
0
: 170 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)
                {
                    filterTable.Rows[filterTable.Rows.IndexOf(filterTable.Select(filterCriterial)[0])].Delete();
                }
            }
        }
        return filterTable;
    }

It should work.

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





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

Full Name *

Email *




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