【问题标题】:How to split pipe-separated (|) values of a column in a datatable and retain other columns in C#如何拆分数据表中列的管道分隔 (|) 值并保留 C# 中的其他列
【发布时间】:2020-11-30 16:48:21
【问题描述】:

我有一个像这样名为 dt1 的数据表

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

我想将用管道分隔 (|) 的第一列拆分为 3 列,并按原样复制其余列

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

有人可以告诉我如何实现这一目标吗?

【问题讨论】:

  • 您需要详细说明您工作的环境以及您希望执行此操作的频率。在 SQL 中,您可以使用 STRING_SPLIT 方法,另一方面,如果您使用 EF 和 C#,您将使用 string.Split 并将结果复制到您将保存到输出表中的新记录。
  • 我已经有一个数据表,看起来像我在 C# 代码中给出的示例。我可以修改或制作新的数据表。我正在使用 C#。

标签: c# asp.net datatable dataset


【解决方案1】:

尝试以下:

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

        }
    }
}

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 2012-01-24
    • 2021-07-26
    • 2019-05-31
    • 1970-01-01
    相关资源
    最近更新 更多