【问题标题】:How to split string by "#" and store result in a DataTable如何用“#”分割字符串并将结果存储在数据表中
【发布时间】:2014-07-04 07:55:20
【问题描述】:

我有这个字符串:

1#3.doc#0.036/n
2#1.doc#0.026/n

我想在# 上拆分它并将每一行放在 DataTable 中的一行中 像这样:

1    3.doc  0.036
2    1.doc  0.026

我有一个这样的数据表:

DataTable table = new DataTable();
table.Columns.Add("Id", typeof(int));
table.Columns.Add("FileName", typeof(string));
table.Columns.Add("Content", typeof(string));

我该怎么做?

【问题讨论】:

  • "split string c#" on google 有 "About 1,940,000 results".. 你试过什么?你研究了什么?
  • @Sayse 这是第一击!
  • @knockando - 这不适合我,如果这是真的,那将是悲伤的一天

标签: c# asp.net split


【解决方案1】:

以下是如何将字符串拆分为行,然后将这些行拆分为不同的部分。

您的字符串首先由换行符\n 拆分为行数组string[]

然后这些行,被Split('#')一一分割成几部分。

最后,这些部分与您创建的列一起添加到您的表格中。

记得保存你创建的列,不要忘记将新创建的行添加到表中。

DataTable table = new DataTable();
DataColumn colID = table.Columns.Add("Id", typeof(int));
DataColumn colFileName = table.Columns.Add("FileName", typeof(string));
DataColumn colContent = table.Columns.Add("Content", typeof(string));

string source = "1#3.doc#0.036\n2#1.doc#0.026\n";

string[] lines = source.Split('\n');

foreach(var line in lines)
{
    string[] split = line.Split('#');

    DataRow row = table.NewRow();

    row.SetField(colID, int.Parse(split[0]));
    row.SetField(colFileName, split[1]);
    row.SetField(colContent, split[2]);

    table.Rows.Add(row);
}

使用row["FileName"] = data 向行添加数据也是可能的,但是如果您更改列的名称,这将中断,同时编译器和您的IDE 检查对列对象的引用。 this article 还解释了如何创建类型化数据表,这是您可能想做的事情。

【讨论】:

  • 我想做这样的事情:(例如)row.SetField(colContent, split[0] + " " + split[1] 但这对我不起作用。
【解决方案2】:

嗯,

var stuff = someString.Split('\n')
    .Select(r => r.Split('#')
    .Select(a => new
        {
            Id = int.Parse(a[0]),
            FileName = a[1],
            Content = a[2]
        })
    .ToList();

这将为您提供匿名类型的IList。不值得将其放入DataTable

【讨论】:

  • 这个问题专门针对DataTable。 “不值得将它放在 DataTable 中”如何作为答案?
  • @data 因为我认为不使用DataTable 会改进OP 的代码。我想不出一个令人信服的理由来使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-05
相关资源
最近更新 更多