C# 如何将数据表的单列的竖线分隔 (|) 值拆分为多列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11862214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split pipe-separated (|) values of a single column of data table into multiple columns
提问by palak mehta
I have a datatable dtRecords. It contains a column Token, which contains pipe- (|) separated values
我有一个数据表dtRecords。它包含一列Token,其中包含竖线 (|) 分隔值
e.g.
例如
234|82|91
235|81|90
237|83|95
238|85|98
I want the output in another table say dtCompleteRecordswith 3 columns a, b, chaving corresponding values of the Tokencolumn of dtRecords.
我想在另一个表中的输出说dtCompleteRecords与3列a, b, c具有的相应值Token的列dtRecords。
Help would be appreciated
帮助将不胜感激
采纳答案by cuongle
try this:
尝试这个:
var dtCompleteRecords = new DataTable("CompleteRecords");
dtCompleteRecords.Columns.Add(new DataColumn("a", typeof(string)));
dtCompleteRecords.Columns.Add(new DataColumn("b", typeof(string)));
dtCompleteRecords.Columns.Add(new DataColumn("c", typeof(string)));
dtRecords.AsEnumerable()
.Select(row => row["Token"].ToString().Split('|'))
.ToList()
.ForEach(array => dtCompleteRecords.Rows.Add(array));
回答by Jan
You are looking for the Split('|')method, that is applied to string. So e.g. myCell.Text.Split('|')
您正在寻找Split('|')应用于字符串的方法。所以例如myCell.Text.Split('|')
回答by Habib
Suppose you have string:
假设你有字符串:
string str = "234|82|91 235|81|90 237|83|95 238|85|98"
Use string.Splitto get an array of string element.
使用string.Split获取字符串元素数组。
string[] strArray = str.Split('|');
Later you can insert these values in the datatable.
稍后您可以将这些值插入到数据表中。
回答by Satinder singh
This will work
这将工作
DataTable dt = yourdatatable;
DataTable dtable2 = new DataTable();
dtable2.Columns.Add("column1", System.Type.GetType("System.String"));
dtable2.Columns.Add("column2", System.Type.GetType("System.String"));
dtable2.Columns.Add("column3", System.Type.GetType("System.String"));
string value = "";
for (int i = 0; i < dt.Rows.Count; i++)
{
value = dt.Rows[0][i].ToString();
string[] splitPipeValue = value.Split('|');
DataRow drow = dtable2.NewRow();
drow[0] = splitPipeValue[0].ToString();
drow[1] = splitPipeValue[1].ToString();
drow[2] = splitPipeValue[2].ToString();
dtable2.Rows.Add(drow);
}
}

