简体   繁体   English

如何用“#”分割字符串并将结果存储在数据表中

[英]How to split string by “#” and store result in a DataTable

I have this string: 我有这个字符串:

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

I want to split it on # and put every line in a single row inside DataTable like this: 我想在#上分割它,并将每一行放在DataTable中的一行中,如下所示:

1    3.doc  0.036
2    1.doc  0.026

I have a DataTable like this: 我有一个这样的数据表:

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

How can I do that? 我怎样才能做到这一点?

Here is how you would split a string into lines, and then those lines into different parts. 这是将字符串拆分为几行,然后将这些行拆分为不同部分的方法。

Your string is first split by the new line character \\n into an array of lines string[] . 您的字符串首先由新的行字符\\n拆分为行数组string[]

Then those lines, one by one, are split into parts by Split('#') . 然后,这些行被Split('#')一一分割。

And finally those parts are added to your table with the columns you created. 最后,这些部分与您创建的列一起添加到您的表中。

Remember to save the columns you created and don't forget to add the newly created row to the table. 记住要保存创建的列,不要忘记将新创建的行添加到表中。

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

Adding data to the row with row["FileName"] = data is also possible, but this will break if you change the name of your column, while references to the column objects are checked by the compiler and your IDE. 也可以将数据添加到具有row["FileName"] = data的行中,但是如果更改列的名称,则此操作会中断,而对列对象的引用将由编译器和IDE检查。 Also this article explains how to create a typed DataTable , which is something you may want to do. 本文还说明了如何创建类型化的DataTable ,这是您可能想要执行的操作。

erm, 嗯,

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

This will give you an IList of an anonymous type. 这将为您提供一个匿名类型的IList Its not worth putting it in a DataTable . 将其放在DataTable中是不值得的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM