알쓸전컴(알아두면 쓸모있는 전자 컴퓨터)
Datatable Merge(병합) 하기 본문
Datatable Merge 하기
public static DataTable DataTableColumnMerge(IList<DataTable> tables, string pkColumnName) { DataTable result; try { if (tables == null || tables.Count == 0) { throw new ArgumentException("Table must not be empty.", "tables"); } if (string.IsNullOrWhiteSpace(pkColumnName)) { throw new ArgumentException("PK Column must not be empty.", "PK Column Name"); } if (!string.IsNullOrWhiteSpace(pkColumnName)) { foreach (DataTable dataTable in tables) { if (!dataTable.Columns.Contains(pkColumnName)) { throw new ArgumentException("All tables must have the specified primaryKey."); } } } if (tables.Count == 1) { result = tables[0]; } else { DataTable dataTable2 = new DataTable(); dataTable2.BeginLoadData(); foreach (DataTable table in tables) { dataTable2.Merge(table); } dataTable2.EndLoadData(); IEnumerable<IGrouping<object, DataRow>> source = from r in dataTable2.AsEnumerable() group r by r[pkColumnName]; IEnumerable<IGrouping<object, DataRow>> enumerable = from g in source where g.Count<DataRow>() > 1 select g; foreach (IGrouping<object, DataRow> source2 in enumerable) { DataRow dataRow = source2.First<DataRow>(); foreach (DataColumn dataColumn in dataTable2.Columns) { DataColumn dc = dataColumn; if (dataRow.IsNull(dc)) { DataRow dataRow2 = source2.Skip(1).FirstOrDefault((DataRow r) => !r.IsNull(dc)); if (dataRow2 != null) { dataRow[dc] = dataRow2[dc]; } } } IEnumerable<DataRow> enumerable2 = source2.Skip(1); foreach (DataRow row in enumerable2) { dataTable2.Rows.Remove(row); } } result = dataTable2; } } catch (Exception ex) { throw ex; } return result; }
실제 함수 사용시에는
DataTable[] ControlChartData; ControlChartData = new DataTable[5]; for(int i = 0; i < 5; i++) { ControlChartData[i] = new DataTable(); } .... 데이터 값을 집어 넣고 DataTable mergetable = DataTableColumnMerge(ControlChartData, "PKColumnName");
'C# tip' 카테고리의 다른 글
Smtp 메일 전송 방법 (0) | 2018.11.16 |
---|---|
CefSharp chrome run javascript (0) | 2018.08.13 |
Datatable 을 csv (엑셀)출력 하는 소스 (0) | 2018.07.19 |
mono linux 최신 버전 build 하기 (0) | 2018.07.11 |
C# restful 만들기 좋은 webserver opensource(embedIO) linux 사용 (0) | 2018.06.26 |
Comments