vb.net 如何从 CSV 文件中读取数据并将信息存储到数组中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14764644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:14:54  来源:igfitidea点击:

How do I read data from a CSV file and store the info Into an array?

arraysvb.netcsv

提问by Gaurav

I have two columns in a CSV file and I need to store each column in a separate array.

我在 CSV 文件中有两列,我需要将每一列存储在一个单独的数组中。

Name,AvalibilityAsBoolean
---------------------------
Vagarth Gaurav,True
Dhananjay Menon,False

I would like to have one array for name, and another array for availability as a boolean value stored similar to below.

我想要一个数组作为名称,另一个数组作为可用性存储为类似于下面的布尔值。

Name(0) = "Vagarth Gaurav"
Name(1) = "Dhananjay Menon"
Available(0) = True
Available(1) = False

The only problem is reading the CSV and storing the strings and booleans into the proper arrays.

唯一的问题是读取 CSV 并将字符串和布尔值存储到正确的数组中。

Please help, I am new to VB. I am using Visual Basic 2010

请帮忙,我是VB的新手。我使用的是 Visual Basic 2010

回答by N0Alias

I'm sure this question has been asked before, but this should help. Utilizing the TextFieldParser Classto do the parsing for you makes it easy. Code for managing the two arrays is displayed in this code example too.

我确定这个问题之前已经问过,但这应该会有所帮助。使用TextFieldParser 类为您进行解析可以很容易。此代码示例中也显示了用于管理两个数组的代码。

    Dim arrName() As String
    Dim arrValue() As String

    Using ioReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\test\test.csv")

        ioReader.TextFieldType = FileIO.FieldType.Delimited
        ioReader.SetDelimiters(",")

        While Not ioReader.EndOfData

            Dim arrCurrentRow As String() = ioReader.ReadFields()

            If arrName Is Nothing Then

                ReDim Preserve arrName(0)
                ReDim Preserve arrValue(0)

                arrName(0) = arrCurrentRow(0)
                arrValue(0) = arrCurrentRow(1)

            Else

                ReDim Preserve arrName(arrName.Length)
                ReDim Preserve arrValue(arrValue.Length)

                arrName((arrName.Length - 1)) = arrCurrentRow(0)
                arrValue((arrValue.Length - 1)) = arrCurrentRow(1)

            End If

        End While

回答by SysDragon

Dim sData() As String
Dim arrName, arrValue as New List(Of String)()

Using sr As New StreamReader(sFile)
    While Not sr.EndOfStream
        sData = sr.ReadLine().Split(","c)

        arrName.Add(sData(0).Trim())
        arrValue.Add(sData(1).Trim())
    End While
End Using

You maybe want to store your value as a Boolean(available, notAvailable). You can do something like:

您可能希望将您的值存储为Boolean(available, notAvailable)。您可以执行以下操作:

Dim arrValue As New List(Of Boolean)()
...

    arrValue.Add(Not sData(1).Trim().ToUpper().StartsWith("NOT"))