将DataTable拆分成多个DataTable代码

实际开发过程中会遇到需要将一个DataTable拆分成多个DataTable(或者一个DataSet)的情况,以下代码经过我正式开发使用:

        /// 
        /// 分解数据表
        /// 
        /// 需要分解的表
        /// 每个表包含的数据量
        /// 
        public DataSet SplitDataTable(DataTable originalTab, int rowsNum)
        {            
            //获取所需创建的表数量
            int tableNum = originalTab.Rows.Count / rowsNum;
 
            //获取数据余数
            int remainder = originalTab.Rows.Count % rowsNum;
            
            DataSet ds = new DataSet();
 
            //如果只需要创建1个表,直接将原始表存入DataSet
            if (tableNum == 0)
            {
                ds.Tables.Add(originalTab.Copy());
            }
            else
            {
                int totalTableCount = remainder > 0 ? tableNum + 1 : tableNum;
                DataTable[] tableSlice = new DataTable[totalTableCount];
            
                //Save orginal columns into new table.            
                for (int c = 0; c < totalTableCount; c++)
                {
                    tableSlice[c] = new DataTable();
                    foreach(DataColumn dc in originalTab.Columns)
                    {                    
                        tableSlice[c].Columns.Add(dc.ColumnName,dc.DataType);                    
                    }
                }                                                            
                //Import Rows
                for (int i = 0; i < totalTableCount; i++)
                {
                    // if the current table is not the last one
                    if (i != totalTableCount - 1)
                    {
                        for(int j = i*rowsNum ; j < ((i+1)*rowsNum); j++)
                        {
                            tableSlice[i].ImportRow(originalTab.Rows[j]);
                        }
                    }
                    else
                    {
                        for(int k = i*rowsNum ; k < (i*rowsNum+remainder); k++)
                        {
                            tableSlice[i].ImportRow(originalTab.Rows[k]);
                        }
                    }
                }            
            
                //add all tables into a dataset                
                foreach(DataTable dt in tableSlice)
                {
                    ds.Tables.Add(dt);
                }
            }
            return ds;
        }

以上代码的原始资料来自网络,经过加工后所得,希望对路过刚好需要的朋友有帮助。

你可能感兴趣的:(C#)