DataTable复制数据,深度复制

时间:2022-05-22 19:56:10
 /**/
    /// <summary>
    /// 复制数据,深度复制
    /// </summary>
    /// <param name="dataSourceRow">数据源,待复制的数据</param>
    /// <param name="dataStruct">数据结构/表结构</param>
    /// <returns>处理后的DataTable</returns>
    public DataTable CopyData(DataRow[] dataSourceRow, DataTable dataStruct)
    {
        DataTable dataTable = new DataTable();
        //定义表结构
        DataColumn col;
        foreach (DataColumn column in dataStruct.Columns)
        {
            col = new DataColumn();
            col.ColumnName = column.ColumnName;
            col.DataType = column.DataType;
            //add column
        }
        foreach (DataRow row in dataSourceRow)
        {
            DataRow tempRow = dataTable.NewRow();
            foreach (DataColumn column in dataStruct.Columns)
            {
                try
                {
                    tempRow[column.ColumnName] = row[column.ColumnName];
                }
                catch
                { continue; }
            }
            dataTable.Rows.Add(tempRow);
        }
        return dataTable;
    }