Sacha
Sacha

Reputation: 164

VB.NET How get previous element while iterating lists?

Is there any way to retrieve previous element or next element while iterating lists in VB.NET? Something like:

For Each item In MyList
   Dim current_item = item
   Dim previous_item = Prev(item)
   Dim next_item = Next(item)
Next

Is there any built-in function which do what imaginary functions "Prev()/Next()" do here? Please answer if there is already an available function, otherwise I know how to write them by myself.

Thanks in advance

Upvotes: 1

Views: 1788

Answers (3)

Enigmativity
Enigmativity

Reputation: 117154

Using the LinkedList(Of T) list my work well for you.

If I can assume that the type of your list is Integer then this works:

Dim MyLinkedList = New LinkedList(Of Integer)(MyList)

Dim node As LinkedListNode(Of Integer) = MyLinkedList.First
While node IsNot Nothing
    Dim current_node = node
    Dim previous_node = node.Previous
    Dim next_node = node.Next

    ' Do stuff in here with `*_node.Value`
    ' Don't forget to check for `Nothing`
    '   in previous and next nodes

    node = node.Next
End While

The only thing that you need to check is if previous_node & next_node are Nothing.

Upvotes: 1

MarkD
MarkD

Reputation: 17

No, the object "item" is unaware of it's place in the collection so it would not be able to look it up itself. Your best bet is to create your own list type and implement the functions if you need to reuse this.

sub Test
    Dim l As New MyCustomList
    l.Add(1)
    l.Add(2)
    l.Add(3)

    For Each o As Object In l
        Dim c As Object = o
        Dim prevo As Object = l.PrevItem(c)
        Dim nexto As Object = l.NextItem(c)
    Next
end sub

Public Class MyCustomList
  Inherits ArrayList

  Public Function PrevItem(item As Object) As Object
      Dim x As Int32 = Me.IndexOf(item)
      If x > 0 Then Return Me.Item(x - 1)
      Return Nothing
  End Function

  Public Function NextItem(item As Object) As Object
      Dim x As Int32 = Me.IndexOf(item)
      If x < Me.Count - 1 Then Return Me.Item(x + 1)
      Return Nothing
  End Function
End Class

Upvotes: 0

Matt Wilko
Matt Wilko

Reputation: 27342

You can iterate by index instead - be sure to check that there is a previous or next item otherwise you'll get an exception:

For i = 0 to MyList.Count - 1
   Dim current_item = MyList(i) 
   Dim previous_item = If(i > 0, MyList(i - 1), Nothing)
   Dim next_item = If(i < MyList.Count - 1 , MyList(i + 1), Nothing)
Next

That way you know exactly where you are at all times.

Remember that For Each does not necessarily mean the order is guaranteed (it depends on the type). See this question for more info Is the .NET foreach statement guaranteed to iterate a collection in the same order in which it was built?

Upvotes: 1

Related Questions