DataTable的行和列混乱

我正在使用C#语言学习库存管理系统的教程。

原始的csv文件是一个库存列表,其中包含四个类别:

Item Code, Item Description, Item Count, OnOrder

原始的csv文件:

在此处输入图片说明

在本教程中,代码将生成一个DataTable对象,该对象将在应用程序的GridView演示中使用。

这是代码:

DataTable dataTable = new DataTable();
            
dataTable.Columns.Add("Item Code");
dataTable.Columns.Add("Item Description");
dataTable.Columns.Add("Current Count");
dataTable.Columns.Add("On Order");

string CSV_FilePath = "C:/Users/xxxxx/Desktop/stocklist.csv";

StreamReader streamReader = new StreamReader(CSV_FilePath);

string[] rawData = new string[File.ReadAllLines(CSV_FilePath).Length];
rawData = streamReader.ReadLine().Split(',');
            
while(!streamReader.EndOfStream)
{
    rawData = streamReader.ReadLine().Split(',');
    dataTable.Rows.Add(rawData[0], rawData[1], rawData[2], rawData[3]);
}

dataGridView1.DataSource = dataTable;

我假设rawData = streamReader.ReadLine().Split(',');将文件分割成这样的数组对象:

["A0001", "Horse on Wheels","5","No"]
["A0002","Elephant on Wheels","2","No"]

在while循环中,它遍历每行(每个数组),并将每个rawData [x]分配到相应的列中。

理解此代码段是否有这种权利?提前致谢。

另一个问题是,为什么我需要跑步

rawData = streamReader.ReadLine().Split(',');

在一段时间循环?

提前致谢。

约翰

您的代码实际上应如下所示:

DataTable dataTable = new DataTable();

dataTable.Columns.Add("Item Code");
dataTable.Columns.Add("Item Description");
dataTable.Columns.Add("Current Count");
dataTable.Columns.Add("On Order");

string CSV_FilePath = "C:/Users/xxxxx/Desktop/stocklist.csv";

using(StreamReader streamReader = new StreamReader(CSV_FilePath))
{
    // Skip the header row
    streamReader.ReadLine();
    
    while(!streamReader.EndOfStream)
    {
        string[] rawData = streamReader.ReadLine().Split(','); // read a row and split it into cells
        dataTable.Rows.Add(rawData[0], rawData[1], rawData[2], rawData[3]); // add the elements from each cell as a row in the datatable
    }
}

dataGridView1.DataSource = dataTable;

我所做的更改:

  • We've added a using block around StreamReader to ensure that the file handle is only open for as long as we need to read the file.
  • We now only read the file once, not twice.
  • Since we only need the rawData in the scope of the while loop, I've moved it into the loop.

Explaining what's wrong:

The following line reads the entire file, and then counts how many rows are in it. With this information, we initialize an array with as many positions as there are rows in the file. This means for a 500 row file, you can access positions rawData[0], rawData[1], ... rawData[499].

string[] rawData = new string[File.ReadAllLines(CSV_FilePath).Length];

With the next row you discard that array, and instead take the cells from the top of the file (the headers):

rawData = streamReader.ReadLine().Split(',');

This line states "read a single line from the file, and split it by comma". You then assign that result to rawData, replacing its old value. So the reason you need this again in the loop is because you're interested in more than the first row of the file.

Finally, you're looping through each row in the file and replacing rawData with the cells from that row. Finally, you add each row to the DataTable:

rawData = streamReader.ReadLine().Split(',');
dataTable.Rows.Add(rawData[0], rawData[1], rawData[2], rawData[3]);

Note that File.ReadAllLines(...) reads the entire file into memory as an array of strings. You're also using StreamReader to read through the file line-by-line, meaning that you are reading the entire file twice. This is not very efficient and you should avoid this where possible. In this case, we didn't need to do that at all.

另请注意,您读取CSV文件的方法非常幼稚。根据用于创建它们的软件的不同,某些CSV文件的单元格跨越文件中的多行,有些包含带引号的文本部分,有时那些带引号的部分包括逗号,这些逗号会抛出分割代码。您的代码也不能解决文件格式错误的问题,例如,一行中的单元格可能比预期的要少,或者文件末尾可能有尾随的空行。通常,最好使用专用的CSV解析器(例如CsvHelper),而不是尝试自己滚动。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章