如何解决如何在数据表中拆分列的管道分隔|值,并在C#
我有一个名为dt1的数据表,
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) });
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。