How to get difference between two DataTables

前端 未结 8 880
自闭症患者
自闭症患者 2020-12-14 17:28

I have these two datatables and I want to get the difference between them. Here is an example:

Table1
-------------------------
ID  |   Name 
---------------         


        
相关标签:
8条回答
  • 2020-12-14 18:20

    Try this

    DataTable dtmismatch = Table1.AsEnumerable().Except(Table2.AsEnumerable(), DataRowComparer.Default).CopyToDataTable<DataRow>();
    
    0 讨论(0)
  • 2020-12-14 18:27

    I just went through this and wanted to share my findings. For my application it is a data sync mechanism, but i think you will see how this applies to the original question.

    In my case, I had a DataTable that represented my last data upload and sometime in the future, I need to get the current state of the data and only upload the differences.

    //  get the Current state of the data
    DataTable dtCurrent = GetCurrentData();
    
    //  get the Last uploaded data
    DataTable dtLast = GetLastUploadData();
    dtLast.AcceptChanges();
    
    //  the table meant to hold only the differences
    DataTable dtChanges = null;
    
    //  merge the Current DataTable into the Last DataTable, 
    //  with preserve changes set to TRUE
    dtLast.Merge(dtCurrent, true);
    
    //  invoke GetChanges() with DataRowState.Unchanged
    //    !! this is the key !!
    //    the rows with RowState == DataRowState.Unchanged 
    //    are the differences between the 2 tables
    dtChanges = dtLast.GetChanges(DataRowState.Unchanged);
    

    I hope this helps. I fought with this for a few hours, and found lots of false-leads on the interwebz, and ended up comparing RowStates after merging a few different ways

    0 讨论(0)
提交回复
热议问题