简体   繁体   中英

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

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?

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM