Home > database >  Turning list contents into a string
Turning list contents into a string

Time:12-14

I have a list with x elements. I need a way that puts the contents of these into a string.

    Dim List As New ArrayList
    Dim Strin As String

    List.Add("Apple")
    List.Add("Bananna")
    List.Add("Carrot")

    For i = 0 To List.Count
        Strin = Strin   List(i)
    Next i
    Console.WriteLine(Strin)

This given an error saying that the index is out of bounds which I don't understand because I start at 0

CodePudding user response:

This exception caused by the last iteration of for loop. As Microsoft documentation says, end part is inclusive, so you should exclude it. Try this:

For i = 0 To List.Count - 1

CodePudding user response:

It goes out of bounds because the index of a list starts from 0. Count is 0 only when your list is empty, if you want to iterate through a populated list you either do:

For i = 1 To List.Count
    Strin = Strin & List(i - 1)
Next i

Or:

For i = 0 To List.Count - 1

Or, my personal favourite:

For Each element in List
  Strin = Strin & element
Next
  • Related