■ Union 확장 메소드를 사용해 DataTable 병합하기 예제

----------------------------------------------------------------------------------------------------

using System.Data;

 

public static DataTable GetTable1()

{

    DataTable table = new DataTable();

 

    table.Columns.Add("ID"  , typeof(string));

    table.Columns.Add("Name", typeof(string));

 

    table.Rows.Add("1", "강남구");

    table.Rows.Add("2", "강동구");

 

    table.AcceptChanges();

 

    return table;

}

 

public static DataTable GetTable2()

{

    DataTable table = new DataTable();

 

    table.Columns.Add("ID"  , typeof(string));

    table.Columns.Add("Name", typeof(string));

 

    table.Rows.Add("2", "강동구");

    table.Rows.Add("3", "광진구");

    table.Rows.Add("4", "중구"  );

 

    table.AcceptChanges();

 

    return table;

}

 

...

 

DataTable table = MergeTable(GetTable1(), GetTable2());

 

...

 

/*

ID Name

-- ------

1  강남구

2  강동구

2  강동구

3  광진구

4  중구

*/

----------------------------------------------------------------------------------------------------

 

■ Union 확장 메소드를 사용해 DataTable 병합하기

----------------------------------------------------------------------------------------------------

using System.Collections.Generic;

using System.Data;

 

#region 테이블 병합하기 - MergeTable(table1, table2)

 

/// <summary>

/// 테이블 병합하기

/// </summary>

/// <param name="table1">테이블 1</param>

/// <param name="table2">테이블 2</param>

/// <returns>병합 테이블</returns>

public DataTable MergeTable(DataTable table1, DataTable table2)

{

    IEnumerable<DataRow> enumerable1 = table1.AsEnumerable();

    IEnumerable<DataRow> enumerable2 = table2.AsEnumerable();

 

    IEnumerable<DataRow> unionEnumerable = enumerable1.Union(enumerable2);

 

    return unionEnumerable.CopyToDataTable();

}

 

#endregion

----------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker
TAG