【问题标题】:c# datatable merge certain rows and columns of datatablec# datatable 合并datatable的某些行和列
【发布时间】:2020-06-17 13:54:48
【问题描述】:

数据表中有6列,我想将column1/rows1和column2/rows2的行和列合并在一起,但保留其余部分。因此,我使用split方法分离了多余的间距,但有单独的数据我想像“ZPRP 09-0729-01-MAR”这样合并在一起变成“ZPRP09-0729-01-MAR”请帮助:D

样本数据:test1.txt

MY01 CISCO ZPRP 08-0729-01-MAR 08-0729-01 1 EA
MY01 思科 ZPRP 08-0729-01-MAR 08-0729-01 1 EA
MY01 思科 ZPRP 08-0729-01-MAR 08-0729-01 1 EA
MY01 思科 ZPRP 10-2919-01$1 10-2919-01 1 EA
MY01 思科 ZPRP 10-2919-01$1 10-2919-01 1 EA
MY01

我想要在数据表上显示的结果:

MY01 CISCO ZPRP08-0729-01-MAR 08-0729-01 1 EA
MY01 思科 ZPRP08-0729-01-MAR 08-0729-01 1 EA
MY01 思科 ZPRP08-0729-01-MAR 08-0729-01 1 EA
MY01 思科 ZPRP10-2919-01$1 10-2919-01 1 EA
MY01 思科 ZPRP10-2919-01$1 10-2919-01 1 EA
MY01

Datatable data

    private void Form1_Load(object sender, EventArgs e)
    {

        DataTable dt = new DataTable();
        string filepath = @"C:\Users\2563911\source\repos\test1.txt";
        using (System.IO.TextReader tr = File.OpenText(filepath))
        {
            string line;
            while ((line = tr.ReadLine()) != null)
            {

                if (!line.StartsWith("-"))
                {
                    if (line.Length < 82 || line.Contains("MY01"))
                    {        
                        string[] items = line.Replace("MY01","").Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

                        if (dt.Columns.Count == 0 )
                        {
                            for (int i = 0; i < items.Length; i++)
                                dt.Columns.Add(new DataColumn("Column" + i, typeof(string)));                                

                        }
                        dt.Rows.Add(items);

                    }
                }
            }

            //show it in gridview
            this.DataGridView.DataSource = dt;
        }
    }
}

}

【问题讨论】:

  • 请提供一些示例数据并提供您期望的输出示例。
  • “合并”是什么意思?在不同的情况下,这可能意味着非常不同的事情。而不是显示您的数据的代码,而是向我们展示您的数据是什么样的,以及您希望它在“合并”后是什么样的。几行就够了。
  • 已编辑,请看一下
  • 也许我没有看到它,但我只能看到“ZPRP 08-0729-01-MAR”现在是“ZPRP08-0729-01-MAR”,其中“P " 和 "0" 被删除,以便为一列形成一个值?
  • 是的,你是对的

标签: c# merge datatable


【解决方案1】:
// The simple solution.
// Split the string at every space.
// Return a new array where you join or re-order the columns however you want.
string[] SplitIntoAndCombineColumns(string line)
{
    var parts = line.Split(' ');

    // Make sure our array is long enough.
    // If the string does not contain these fields,
    // they will be null in the result.
    if(parts.Length < 7) {
        Array.Resize(ref parts, 7);
    }

    var result = new[] {
        parts[0], parts[1], 
        // Combine these two columns
        parts[2] + parts[3],        
        parts[4], parts[5], parts[6]
    };

    return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 2020-01-21
    • 2019-06-02
    • 2017-09-02
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    相关资源
    最近更新 更多