C# 通用DataTable 拆分小表
一个简单的使用遍历的方式进行DataTable 的拆分private static List<DataTable> DataTableSplite(DataTable dt, int modcounts)
{
List<DataTable> list = new List<DataTable>();
int counts = dt.Rows.Count / modcounts; /// 取整数个数
int mod = dt.Rows.Count % modcounts; /// 余数
if (mod > 0)
{
int index = 0;
/// 处理拆分倍数的部分
for (int i = 0; i < counts; i++)
{
DataTable dt1 = dt.Clone();
dt1.TableName = "count" + i;
for (int j = index * modcounts; j < (index + 1) * modcounts; j++)
{
DataRow newrow = dt.NewRow();
DataRow row1 = dt.Rows[j];
newrow["name"] = row1["name"];
newrow["age"] = row1["age"];
dt1.Rows.Add(newrow.ItemArray);
}
index++;
list.Add(dt1);
}
/// 处理余数部分的组合
DataTable dt2 = dt.Clone();
dt2.TableName = "modetable";
for (int i = counts * modcounts; i < dt.Rows.Count; i++)
{
DataRow newrow = dt.NewRow();
DataRow row1 = dt.Rows[i];
newrow["name"] = row1["name"];
newrow["age"] = row1["age"];
dt2.Rows.Add(newrow.ItemArray);
}
list.Add(dt2);
}
else
{
/// 余数为0 的情况处理
int index = 0;
for (int i = 0; i < counts; i++)
{
DataTable dt1 = dt.Clone();
dt1.TableName = "modetable";
for (int j = index * modcounts; j < (index + 1) * modcounts; j++)
{
DataRow newrow = dt.NewRow();
DataRow row1 = dt.Rows[j];
newrow["name"] = row1["name"];
newrow["age"] = row1["age"];
dt1.Rows.Add(newrow.ItemArray);
}
index++;
list.Add(dt1);
}
}
return list;
} 实现的方式比较简单,同时也可以使用linq 的方式进行
代码如下:private static List<DataTable> DataTableSplite2(DataTable dt, int modcounts)
{
int counts = dt.Rows.Count / modcounts; /// 取整数个数
List<DataTable> list = new List<DataTable>(); ///
int index = 0;
for (int i = 0; i < counts + 1; i++)
{
list.Add(dt.AsEnumerable().Skip(index * modcounts).Take(modcounts).CopyToDataTable());
index++;
}
return list;
} 代码更少。
·
|