Bienvenido Omosura Bienvenido Omosura - 1 month ago 11
C# Question

Comparing two DataTables to determine if it is modified

I have two DataTables:

DataTable original;

DataTable modified;


The two tables has the same number of rows and their columns and datas is the same.

I want my
modified
datable to determine each row to compare to the
original
datatable . If a row from the
modified
datatable is not equal to the row of
original
datatable then the row's
.RowState
will be set to
.SetModified()
from the
modified
datatable.

For Example:

...................................................

if row1 in
orginal
is not equal to row1 in
modified
then
row1.SetModified()


if row2 in
orginal
is not equal to row2 in
modified
then row2.SetModified()
....etc

............................................................

it should not be like this:

............................................................

if row1 in
orginal
is not equal to row2 in
modified
then
row1.SetModified()


if row2 in
orginal
is not equal to row3 in
modified
then
row1.SetModified()
...etc

............................................................

get the idea? :)

Any code suggestion without using
Primary Keys
?

Answer

Using foreach loop within another foreach is N X N comparison, that you don't need to do.

Comparing First row with First row of other table, second with second and so on using Zip extension method is very useful for this case.

DataTable original;
DataTable modified;

// your stuff

modified = modified.AsEnumerable().Zip<DataRow, DataRow, DataRow>(original.AsEnumerable(), (DataRow modif, DataRow orig) =>
{
    if (!orig.ItemArray.SequenceEqual<object>(modif.ItemArray))
    {
        modif.SetModified();
    }
    return modif;
}).CopyToDataTable<DataRow>();