You cannot modify a collection while you list it, as in the first example. Instead, you should get a list of rows to delete, and then delete them.
List<DataRow> rowsToDelete = new List<DataRow>(); foreach (DataRow DR in DTTable2.Rows) { if (DR["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString()) rowsToDelete.Add(DR); } foreach (var r in rowsToDelete) DTTable2.Rows.Remove(r);
Or, built using linq:
DTTable2.Rows .Where(DR => DR["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString()) .ToList() .ForEach(r => DTTable2.Rows.Remove(r));
The second example failed, because after deleting a row, the indices of subsequent rows change, but you continue to increment i , which actually skips the row immediately after the deleted row. There are two ways:
for (int i = DTTable2.Rows.Count - 1; i >= 0; i--) if (DTTable2.Rows[i]["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString()) DTTable2.Rows.RemoveAt(i);
or
int i = 0; while (i < DTTable2.Rows.Count) { if (DTTable2.Rows[i]["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString()) DTTable2.Rows.RemoveAt(i); else i++; }
Side note. I wonder if you really want to compare the data of line 0 with this description. Perhaps you wanted to compare all lines similar to the following (although not optimal)?
if (DTTable1.Any(r => DTTable2.Rows[i]["ItemID"].ToString() == r["ItemID"].ToString()))
source share