2013-06-04 2 views
0

조건에 따라 합계 또는 평균을 사용하여 DataTable을 목록에 병합하고 싶습니다. 예를 들면 다음과 같습니다.조건이있는 데이터 테이블 병합

private DataTable getData(List<DataTable> datas, string[] KeyColumnNames, string valueCol) 
{ 
    List<DataTable> dataTables = datas; 
    //if datas has 3 dataTables in it : dt1, dt2, dt3 
    // then I want to create another dataTable dtAll which will have the sum of 
    // valueCol of all three datatables for the row which will be conditioned using 
    // KeyColumnNames (can be multiple Primary keys) 
    return dataTable; 
} 

모든 데이터 테이블은 유사한 스키마이지만 데이터 센터가 다른 테이블과 동일하지만 값이 다른 것으로 간주하십시오. 감사합니다. .

+0

LINQ를 사용하면 통합뿐만 아니라 결합도 할 수 있습니다. –

답변

1

나는 Union 방법은 난이 도움이되기를 바랍니다 다음

public static DataTable Union(DataTable First, DataTable Second, string strReturnedTableName) 
{ 
    // Result table. 
    DataTable table = new DataTable(strReturnedTableName); 

    // Build new columns. 
    DataColumn[] newcolumns = new DataColumn[First.Columns.Count]; 
    for (int i = 0; i < First.Columns.Count; i++) 
     newcolumns[i] = new DataColumn(First.Columns[i].ColumnName, First.Columns[i].DataType); 

    // Add new columns to result table. 
    table.Columns.AddRange(newcolumns); 
    table.BeginLoadData(); 

    // Load data from first table. 
    foreach (DataRow row in First.Rows) 
     table.LoadDataRow(row.ItemArray, true); 

    // Load data from second table. 
    foreach (DataRow row in Second.Rows) 
     table.LoadDataRow(row.ItemArray, true); 

    table.EndLoadData(); 
    return table; 
} 

처럼 뭔가에 의해 정의된다

List<DataTable> dataTableList = dtList; 
DataTable unionDataTable = new DataTable(); 
for(int i = 0; i < dtList.Count; i++) 
    unionDataTable = Union(unionDataTable, dtList[i], "UnionDataTable"); 

할 것입니다.

편집. 메소드에 Action을 전달하고 이것을 foreach 블록에서 사용하여 원하는 것을 할 수 있습니다.

+0

이것은 데이터를 병합하기 만하면됩니다. 데이터에 대한 연산을 수행해야합니다. unionDataTable의 열 값과 같은 값은 모든 테이블의 값 합계 또는 평균을가집니다. – Ratan

+1

편집을 참조하십시오. 전체 코드를 작성할 수는 없지만 위의 코드는 좋은 시작이어야합니다 ... – MoonKnight