问题描述
name age color
a|b|c 20 red
d|e|f 30 green
x|y|z 40 blue
我想将管道分隔的第一列(|)分为3列,并按原样复制其余列
n1 n2 n3 age color
a b c 20 red
d e f 30 green
x y z 40 blue
有人可以建议我如何实现这一目标吗?
解决方法
尝试以下操作:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataTable dt1 = new DataTable();
dt1.Columns.Add("name",typeof(string));
dt1.Columns.Add("age",typeof(int));
dt1.Columns.Add("color",typeof(string));
dt1.Rows.Add(new object[] {"a|b|c",20,"red"});
dt1.Rows.Add(new object[] {"d|e|f",30,"green"});
dt1.Rows.Add(new object[] { "x|y|z",40,"blue" });
DataTable dt2 = new DataTable();
dt2.Columns.Add("n1",typeof(string));
dt2.Columns.Add("n2",typeof(string));
dt2.Columns.Add("n3",typeof(string));
dt2.Columns.Add("age",typeof(int));
dt2.Columns.Add("color",typeof(string));
foreach (DataRow row in dt1.AsEnumerable())
{
string[] splitData = row.Field<string>(0).Split(new char[] {'|'});
dt2.Rows.Add(new object[] { splitData[0],splitData[1],splitData[2],row.Field<int>(1),row.Field<string>(2) });
}
}
}
}