Hello
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 =>
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
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.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly