英文:
split one column to two in datatable c#
问题
I have a dataTable with one column. I want to split it into two columns based on the column value.
My datatable looks like this:
Message
--------
PR-111 : test message
The output should be like this:
PRNo    Message
------  -----------
PR-111  test message
I have tried to loop through the datatable and create the rows by splitting the column value like this, 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?
英文:
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
得分: 1
你可以使用 linq 来完成这个任务。为了使 dataTable 可以在 linq 中使用,它必须经过 AsEnumerable() 处理。
var r = dt1.AsEnumerable().Select(g => new { PRNumber = g["Message"].ToString().Split(':')[0],
                                             Message = g["Message"].ToString().Split(':')[1] }).ToList();
英文:
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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论