Datatable from List

后端 未结 1 1206
迷失自我
迷失自我 2021-01-22 21:07

I have downloaded data that is contained in a List Rows like this:

class Row
{
    string[] Items { get; set; }
    public Row(string[] I         


        
相关标签:
1条回答
  • 2021-01-22 21:36

    Your code is a bit contradictory. You are trying to copy properties as column names, however your csv code actually populates the first row as the column names. You have no distinction between header rows and data rows

    You can just read it straight into a datatable with something like :-

    (though you may want to do better error checking)

    var dt = new DataTable("Rows");
    string data = "a,b,c\r\n1,2,3\r\n4,5,6";
    var stream = GenerateStreamFromString(data); // http://stackoverflow.com/questions/1879395/how-to-generate-a-stream-from-a-string
    
    using (var reader = new StreamReader(stream))
    {
        reader.ReadLine()?.Split(',').ToList().ForEach(h => dt.Columns.Add(h));
        while (!reader.EndOfStream)
        {
            dt.Rows.Add(reader.ReadLine()?.Split(',').ToArray());
        }
    }
    foreach (DataColumn dataColumn in dt.Columns)
    {
        Console.Write($"{dataColumn.ColumnName} ");
    }
    Console.WriteLine();
    
    foreach (DataRow dataRow in dt.Rows)
    {
        Console.Write("Row: ");
        foreach (var item in dataRow.ItemArray)
        {
            Console.Write(item + " ");
        }
        Console.WriteLine();
    }
    
    0 讨论(0)
提交回复
热议问题