2D字符串列表的长度不返回正确的值

时间:2016-04-14 10:39:33

标签: vb.net

我在2D字符串列表中使用.count时遇到问题。这是代码:

If File.Exists(fullPath) = True Then
        Dim readText() As String = File.ReadAllLines(fullPath)
        Dim s As String
        accountCounter = 0

        For Each s In readText
            accountList.Add(New List(Of String))
            accountList.Add(New List(Of String))
            accountList.Add(New List(Of String))

            accountList(accountCounter).Add(s.Split(",")(0))
            accountList(accountCounter).Add(s.Split(",")(1))
            accountList(accountCounter).Add(s.Split(",")(2))
            accountCounter += 1
        Next
        print_logs(accountList.count)
    End If

结果如下:

  

{{名称,电子邮件,密码},{NAME2,EMAIL2,密码2},{NAME3,EMAIL3,password3},{NAME4,EMAIL4,password4}}

在文件中有以下几行:
姓名,电子邮件,密码
NAME2,EMAIL2,密码2
NAME3,EMAIL3,password3
name4,email4,password4

但数据不是问题,真正的问题是Count方法,它返回(12)。我认为它会返回4 * 3的结果,因为如果我在代码中添加它:

print_logs(accountList(0).Count)

它正确返回3.

那么,我怎么才能回归4?

1 个答案:

答案 0 :(得分:2)

在此代码中,每次进行迭代时都会创建三个新行...如果文本文件中有四行,那么您将创建十二行...

请改为:

If File.Exists(fullPath) = True Then
    Dim readText() As String = File.ReadAllLines(fullPath)
    Dim s As String
    accountCounter = 0

    For Each s In readText
        accountList.Add(New List(Of String))
        accountList(accountCounter).Add(s.Split(",")(0))
        accountList(accountCounter).Add(s.Split(",")(1))
        accountList(accountCounter).Add(s.Split(",")(2))
        accountCounter += 1
    Next
    print_logs(accountList.count)
End If

如果你想让它变得更好:

If File.Exists(fullPath) = True Then
    Dim readText() As String = File.ReadAllLines(fullPath)

    For Each s As String In readText
        Dim newList = New List(Of String)

        newList.Add(s.Split(",")(0))
        newList.Add(s.Split(",")(1))
        newList.Add(s.Split(",")(2))
        accountList.Add(newList)
    Next
    print_logs(accountList.count)
End If