分离数据表中的一列为两列,C#。

huangapple go评论71阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年5月6日 18:27:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76188388.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定