Lists elements are overwritten while adding a list to a list

I have the following code:

Dim innerList As New List(Of String)
Dim outerList As New List(Of List(Of String))

For Each ds As datasource In datasources

    selectedIdentifier = ds.identifier

    Dim columnInfos As New List(Of Columns)
    columnInfos = client.getColumns(token, selectedIdentifier)

    For Each colInfo As Columns In columnInfos
        innerList.Add(colInfo.code)
    Next

    outerList.Add(innerList)
    innerList.Clear()
Next

What I try to do is the following thing. I have different datasources. All of these datasources have different columnnames (=.code) while the number of columns is different too. I want to store the columnnames of one datasource in a list (innerlist) and store all these lists in another list (outerList).

What I do not understand is: Setting a stopper at line: outerList.Add(innerList) the list holds the right data for the current datasource in the first iteration. Coming to the second iteration the list holds the data of the second datasource twice (apparentely the data of the first dataset is overwritten with the data of the first dataset). So the data of

outerlist (i) j and outerlist (i+1) j 

are the same and I just do not see why this is happening?

Jon Skeet
people
quotationmark

You're creating a single list for innerList, and adding that reference to outerList on each iteration... so your outerList ends up containing lots of references to the same list, which ends up empty because you clear it. You should create a new list on each iteration - I'd declare innerList in the loop as well:

Dim outerList As New List(Of List(Of String))

For Each ds As datasource In datasources
    Dim innerList As New List(Of String)

... and remove the call to Clear() at the end, as otherwise you'll end up with lots of references to different empty lists.

Note that all of this would be a lot simpler using LINQ - you could do the whole thing in a more declarative way in about 5 lines of code. I'd show those lines, but as query syntax in VB is somewhat different to C#, I would probably get it wrong - you should look into LINQ though...

people

See more on this question at Stackoverflow