Merge 2 DataTables and store in a new one

后端 未结 5 1864
别那么骄傲
别那么骄傲 2020-11-28 11:14

If I have 2 DataTables (dtOne and dtTwo) and I want to merge them and put them in another DataTable (dtAll). How can I do this in C#? I tried the Merge statement on the da

相关标签:
5条回答
  • 2020-11-28 11:24

    (Quite late, but might help someone stumbling upon this question.)

    Instead of dtAll = dtOne.Copy(); in Jeromy Irvine's answer you can do:

    dtAll = new DataTable();
    ...
    dtAll.Merge(dtOne);
    dtAll.Merge(dtTwo);
    dtAll.Merge(dtThree);
    ...
    

    and so on.

    This technique is useful in a loop where you want to iteratively merge data tables:

    DataTable dtAllCountries = new DataTable();
    
    foreach(String strCountry in listCountries)
    {
        DataTable dtCountry = getData(strCountry); //Some function that returns a data table
        dtAllCountries.Merge(dtCountry);
    }
    
    0 讨论(0)
  • 2020-11-28 11:27
    dtAll = dtOne.Copy();
    dtAll.Merge(dtTwo,true);
    

    The parameter TRUE preserve the changes.

    For more details refer to MSDN.

    0 讨论(0)
  • 2020-11-28 11:32

    The Merge method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both.

    If you want to preserve both of the original tables, you could copy the original first, then merge:

    dtAll = dtOne.Copy();
    dtAll.Merge(dtTwo);
    
    0 讨论(0)
  • 2020-11-28 11:35
    DataTable dtAll = new DataTable();
    DataTable dt= new DataTable();
    foreach (int id in lst)
    {
        dt.Merge(GetDataTableByID(id)); // Get Data Methode return DataTable
    }
    dtAll = dt;
    
    0 讨论(0)
  • 2020-11-28 11:46

    This is what i did for merging two datatables and bind the final result to the gridview

            DataTable dtTemp=new DataTable();
            for (int k = 0; k < GridView2.Rows.Count; k++)
            {
                string roomno = GridView2.Rows[k].Cells[1].Text;
                DataTable dtx = GetRoomDetails(chk, roomno, out msg);
                if (dtx.Rows.Count > 0)
                {
                    dtTemp.Merge(dtx);
                    dtTemp.AcceptChanges();
    
                }
            }
    
    0 讨论(0)
提交回复
热议问题