Merge 2 DataTables and store in a new one

后端 未结 5 1874
别那么骄傲
别那么骄傲 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);
    }
    

提交回复
热议问题