Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two DataTables to determine if it is modified

Tags:

c#

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?

like image 607
Bienvenido Omosura Avatar asked Jan 20 '26 15:01

Bienvenido Omosura


2 Answers

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>();
like image 90
Sarvesh Mishra Avatar answered Jan 23 '26 05:01

Sarvesh Mishra


Try this

foreach (DataRow row1 in original.Rows)
    {
        foreach (DataRow row2 in modified.Rows)
        {
            var array1 = row1.ItemArray;
            var array2 = row2.ItemArray;

            if (array1.SequenceEqual(array2))
            {
              // Your logic
            }
            else
            {
              // Your logic
            }
        }
    }

Reference

like image 39
Manoj Avatar answered Jan 23 '26 05:01

Manoj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!