terzi_matte
terzi_matte

Reputation: 175

Length of 2D String list does not return the right value

I have a problem when I use .count in my 2D String list. This is the code:

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

The result is this:

{{name,email,password},{name2,email2,password2},{name3,email3,password3},{name4,email4,password4}}

beacuse in the file there are the following lines:
name,email,password
name2,email2,password2
name3,email3,password3
name4,email4,password4

But data is not the problem, the real problem is the Count method, it returns (12). I think that it returns 4 * 3 result, because if I add this in the code:

print_logs(accountList(0).Count)

it correctly returns 3.

So, how can I just return 4?

Upvotes: 0

Views: 44

Answers (1)

Martin Verjans
Martin Verjans

Reputation: 4806

In this code you create three new rows everytime you do an iteration... If there are four lines in your text files then you will create twelve...

Do this instead :

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

And if you want to make it even better :

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

Upvotes: 2

Related Questions