把一个Datatable的列复制到另一个datatable的列中
datatable1
id name age
1 aa 11
2 bb 12
3 cc 12
... ... ...
要把datatable1中的Name列(包括数据)复制到 datatable2中,代码该怎么写 ?DataTable? 数据
[解决办法]
foreach循环付值,最好从数据库中查询出来,通过 linq语句关联得到datatable2
[解决办法]
refer:
DataTable dt1 = new DataTable();
dt1.Columns.Add("id", typeof(Int32));
dt1.Columns.Add("name", typeof(String));
dt1.Columns.Add("age", typeof(Int32));
DataRow dr = null;
dr = dt1.NewRow();
dr["id"] = 1;
dr["name"] = "aa";
dr["age"] = 11;
dt1.Rows.Add(dr);
dr = dt1.NewRow();
dr["id"] = 2;
dr["name"] = "bb";
dr["age"] = 12;
dt1.Rows.Add(dr);
dr = dt1.NewRow();
dr["id"] = 3;
dr["name"] = "cc";
dr["age"] = 13;
dt1.Rows.Add(dr);
DataTable dt2 = new DataTable();
dt2.Columns.Add("name", typeof(String));
dt1.AsEnumerable().ToList().ForEach(x => dt2.Rows.Add(x.Field<string>("name")));
dt2.AsEnumerable().ToList().ForEach(x => Console.WriteLine(x.Field<string>("name")));//输出aa、bb、cc
select top 0 * into datatable2 from datatable1
如果datatable1中id是自增,要把datatable2中自增去掉
insert into datatable2(id,name,age ) select id,name,age from datatable1;