split one column to two in datatable c#

189 views Asked by At

I have a dataTable with one column. I want to split into two column based on the column value

My datatable looks like below

Message
--------
PR-111 : test message

Output should be like below

PRNo    Message
------  -----------
PR-111  test message

I have tried to loop through the datatable and create the rows by splitting the column value like below but that is not the efficient way .

 DataTable dt1Copy = new DataTable();

        dt1Copy.Columns.Add("PRNumber", typeof(string));
        dt1Copy.Columns.Add("Message", typeof(string));

        foreach (DataRow drNew in dt1.Rows)
        {
            string message = Convert.ToString(drNew["Message"]);
            var listData = message.Split(':').ToList();

            DataRow drCreated = dt1Copy.NewRow();

            drCreated["PRNumber"] = listData[0];
            drCreated["Message"] = listData[1];

            dt1Copy.Rows.Add(drCreated);

        }

Can anyone please suggest a better way to do this ?

1

There are 1 answers

1
Hossein Sabziani On

You can use linq for this. In order for the dataTable to be usable in the linq, it must be AsEnumerable()

var r = dt1.AsEnumerable().Select(g =>new {PRNumber= g["Message"].ToString().Split(':')[0] ,
                           Message = g["Message"].ToString().Split(':')[1] }).ToList();