简体   繁体   中英

C# - Write to a datatable from delimited string

I have a string something like this:

"X","Y","Z"
"X2","Y2","Z2"

ie, Multiple rows seperated by a new line containing multiple different string values delimited by commas.

How could I create a function to input these values into a datatable like this:

"X" "Y" "Z"
"X2" "Y2" "Z2"

for any number of rows and columns in my string?

Here's what I have so far:

public static DataTable writeToDT(string data) //Write to datatable from string
    {
        DataTable dataTable = new DataTable();
        foreach (string header in csvHeader)
        {
            dataTable.Columns.Add(header);
        }
        using (StringReader reader = new StringReader(data))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                DataRow dataRow = dataTable.NewRow();
            }
        }
        return dataTable;
    }

Where csvheader is an array already filled with the headers in my data.
I believe this creates an empty datatable with the right amount of rows and columns, but I'm not sure how to fill it with the string data I have.

Thanks in advance.

Something like this should work. Parsing CSV is a solved problem, the TextFieldParser class in the using Microsoft.VisualBasic.FileIO; namespace (add a reference to Microsoft.VisualBasic ) can do this for you.

public static DataTable WriteToDataTable(string data)
{
    DataTable dataTable = new DataTable();
    foreach (var header in csvHeader)
        dataTable.Columns.Add(header);

    using (var reader = new StringReader(data))
    {
        TextFieldParser csvParser = new TextFieldParser(reader) { HasFieldsEnclosedInQuotes = true, Delimiters = new string[] { "," } };

        while (!csvParser.EndOfData)
        {
            var dataTableRow = dataTable.NewRow();
            dataTableRow.ItemArray = csvParser.ReadFields();
            dataTable.Rows.Add(dataTableRow);
        }
    }
    return dataTable;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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