Split string by # and store result in a datatable

I have this string:



I want to split it on # and put every line in a single row inside DataTable like this:

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?

Last updated:11/14/2014 6:20:38 AM

1 Answers

Anonymous User
Anonymous User

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[].

Then those lines, one by one, are split into parts by 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]);

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. Also this article explains how to create a typed DataTable, which is something you may want to do.