Emi
Emi

Reputation: 306

List of lists in vb.net


I am trying to create lists, that are then inserted into another list. For some reason the latter list gets overwritten each time I try to add new list item to it.

For the code below, first I want to add items to Temp list and after certain conditions have been met, add the Temp list as an item to the Comp list. After that, the cycle repeats, new and different Temp list should be created and the added to the Comp list as next item. So each item in Comp list should be different.

But in the end I get a Comp list that is filled with Temp lists that are all identical to the last Temp list added.
What am I doing wrong?

Function UniqueValueList2(ByVal InputObject As List(Of Object)) As List(Of List(Of Object))
    Dim vc As Integer = InputObject.Count
    Dim i As Integer = 1
    Dim Temp As New List(Of Object)
    Dim Comp As New List(Of List(Of Object))

    Dim CurrentObj As String
    Dim PrevObj As String

    Temp.Add(InputObject(0))

    Do While i < vc
        CurrentObj = InputObject(i).fieldName
        PrevObj = InputObject(i-1).fieldName

        If CurrentObj = PrevObj Then
            Temp.Add(InputObject(i))
        Else
            Comp.Add(Temp)
            Temp.Clear()
            Temp.Add(InputObject(i))
        End If
        i = i + 1
    Loop
    Comp.Add(Temp)
    UniqueValueList2 = Comp
End Function

Upvotes: 0

Views: 5370

Answers (2)

Isildur
Isildur

Reputation: 40

This will work:

Comp.Add(Temp.ToList())
Temp.Clear()
Temp.Add(InputObject(i))

Upvotes: 1

qwr
qwr

Reputation: 3670

Temp is holding the same reference. so making changes on it will change it.And you add and modify the same List

 Comp.Add(Temp) 'the same Temp List
 Temp.Clear() 'You will clear the same List
 Temp.Add(InputObject(i))

So How you should do :

Comp.Add(Temp) 'we add old List
Temp=New List(Of Object) 'Temp now holds reference to new List
Temp.Add(InputObject(i))

Upvotes: 4

Related Questions