.NET Datable分解数据表
/// <summary>
/// 分解数据表
/// </summary>
/// <param name="originalTab">需要分解的表</param>
/// <param name="rowsNum">每个表包含的数据量</param>
/// <returns></returns>
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);
}
else
{
/////////////////////////////////////
//如果不能整除则需要+1
if (remainder != 0)
{
tableNum += 1;
}
/////////////////////////////////////
DataTable[] tableSlice = new DataTable[tableNum];
//将原始列保存到新表中 .
for (int c = 0; c < tableNum; c++)
{
tableSlice[c] = new DataTable();
foreach (DataColumn dc in originalTab.Columns)
{
tableSlice[c].Columns.Add(dc.ColumnName, dc.DataType);
}
}
//导入行
for (int i = 0; i < tableNum; i++)
{
// 如果当前表不是最后一个表
if (i != tableNum - 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 + 1) * rowsNum + remainder); k++)
{
try
{
tableSlice[i].ImportRow(originalTab.Rows[k]);
}
catch (Exception ex)
{
}
}
}
}
//将所有表添加到数据集中
foreach (DataTable dt in tableSlice)
{
ds.Tables.Add(dt);
}
}
return ds;
}
调用实例
public dynamic GetDeta(Guid Gid)
{
var sql = new SqlModel(DBUtility.DBType.Sql)
{
ExecuteType = SqlExecuteType.DataTable,
Sql = @"SELECT
m.ShopCode,
m.SaleQty
FROM dbo.Shop(nolock)",
Where = " WHERE Gid=@Gid ",
DbParameter = new List<DbParameter> {
DBHelper.CreateInDbParameter("Gid", Gid)
}
};
var dt = DBHelper.ExecuteSqlModel<DataTable>(sql);
DataSet GroupData=new DataSet();
if (dt.Rows.Count > 0)
{
GroupData = SplitDataTable(dt, 3);
}
return GroupData;
}