How to split pipe-separated (|) values of a column in a datatable and retain other columns in C#

I have a datatable named dt1 like this

name    age  color
a|b|c   20   red
d|e|f   30   green
x|y|z   40   blue

I want to split the first column that is pipe-separated (|) into 3 columns and copy the rest of the columns as it is

n1  n2  n3  age  color
a   b   c   20   red
d   e   f   30   green
x   y   z   40   blue

Can someone please advice me on how to achieve this?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Try following :

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) });
            }

        }
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x