Reputation: 127
I have two DataTables with the same columns:
DataTable dt;
DataTable posTable;
Sometimes they can have different numbers of row..
I want to delete a row from the table if it exists in another..
I tried using this code:
dt = dt.AsEnumerable().Zip<DataRow, DataRow, DataRow>(posTable.AsEnumerable(), (DataRow modif, DataRow orig) =>
{
if (orig.ItemArray.SequenceEqual<object>(modif.ItemArray))
{
modif.Delete();
}
return modif;
}).CopyToDataTable<DataRow>();
dt.AcceptChanges();
but it didn't work :( [it only deletes what's not exists in another] i tried turning it around but gives me errors.
Any code suggestion?
Upvotes: 0
Views: 2371
Reputation: 460228
Yes, you can use SequenceEqual
but you have to use Remove
instead of Delete
. The latter deletes them from database if you use a DataAdapter
, the former removes them from the table.
Another approach is filtering with LINQ and using CopyToDataTable
on the remaining rows:
var rows1 = dt.AsEnumerable();
var rows2 = posTable.AsEnumerable();
dt = rows1
.Where(r1 => !rows2.Any(r2 => r1.ItemArray.SequenceEqual(r2.ItemArray)))
.CopyToDataTable();
This keeps only non-duplicate rows because of the !rows2.Any
in the Where
-filter.
Upvotes: 1
Reputation: 84
This link also examples about Compare two tables
http://www.codeproject.com/Questions/686406/How-To-Compare-and-delete-datatable-row-using-Csha
Or
I think this example is use for you..
DataTable dt1 = new DataTable();
dt1.Columns.Add("Name");
dt1.Rows.Add("Apple");
dt1.Rows.Add("Banana");
dt1.Rows.Add("Orange");
DataTable dt2 = new DataTable();
dt2.Columns.Add("Name");
dt2.Rows.Add("Apple");
dt2.Rows.Add("Banana");
List<DataRow> rows_to_remove = new List<DataRow>();
foreach (DataRow row1 in dt1.Rows)
{
foreach (DataRow row2 in dt2.Rows)
{
if (row1["Name"].ToString() == row2["Name"].ToString())
{
rows_to_remove.Add(row1);
}
}
}
foreach (DataRow row in rows_to_remove)
{
dt1.Rows.Remove(row);
dt1.AcceptChanges();
}
Upvotes: 1