如何按列将数据表拆分为两个单独的数据表 [英] How to split a DataTable in two separate by columns

查看:38
本文介绍了如何按列将数据表拆分为两个单独的数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据表,它有很多列,只有一行:

I have a DataTable which has many columns and only one row:

...
DataSet myDataSet = new DataSet();
da.Fill(myDataSet);

myDataTable = new DataTable();
myDataTable = myDataSet.Tables[0];
...

如何拆分 DataSet/DataTable 以使其具有相等数量的列(如果它是奇数,则拆分列以便第一个 DataTable 具有额外的列).

How can I split the DataSet/DataTable to have equal amount of columns (if it is an odd number, split the columns so the first DataTable has the extra column).

场景 #1:

DataTable:

col1    col2    col3    col4    col5    col6    col7    col8
9       0       9       5       7       4       9       3

DataTable1:

col1    col3    col3    col4
9       0       9       5

DataTable2:

col5    col6    col7    col8
7       4       9       3

场景#2:

DataTable:

col1    col2    col3    col4    col5    col6    col7
9       0       9       5       7       4       9

DataTable1:

col1    col3    col3    col4
9       0       9       5

DataTable2:

col5    col6    col7
7       4       9

推荐答案

可以复制整个数据表,然后删除不需要的列.

You can copy the whole data table and then remove the columns you don't want.

对于您的第一个示例,以下代码将返回数据表 1 中的前四列和数据表 2 中的其余列.

So for your first example, following code will return first four columns in datatable1 and remaining columns in datatable 2.

您可以根据列数修改代码

You can modify your code as per your number of columns

DataTable dataTable1;
dataTable1 = myDataTable.Copy();
dataTable1.Columns.RemoveAt(4);
dataTable1.Columns.RemoveAt(5);
dataTable1.Columns.RemoveAt(6);
dataTable1.Columns.RemoveAt(7);

DataTable dataTable2;
dataTable2 = myDataTable.Copy();
dataTable2.Columns.RemoveAt(0);
dataTable2.Columns.RemoveAt(1);
dataTable2.Columns.RemoveAt(2);
dataTable2.Columns.RemoveAt(3);

这篇关于如何按列将数据表拆分为两个单独的数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆