VB.NET如何在迭代列表时获取前一个元素?

时间:2016-04-20 13:39:07

标签: .net vb.net list iteration

有没有办法在VB.NET中迭代列表时检索前一个元素或下一个元素? 类似的东西:

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

是否有任何内置函数可以执行虚构函数“ Prev()/ Next()”吗? 请回答是否已有可用功能,否则我知道如何自己编写。

提前致谢

3 个答案:

答案 0 :(得分:1)

您可以通过索引进行迭代 - 请务必检查是否存在上一个或下一个项目,否则您将获得例外:

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

这样你就可以随时知道自己到底在哪里。

请记住,For Each并不一定意味着订单得到保证(取决于类型)。有关详细信息,请参阅此问题Is the .NET foreach statement guaranteed to iterate a collection in the same order in which it was built?

答案 1 :(得分:1)

使用LinkedList(Of T)列表,我的工作很适合你。

如果我可以假设您的列表类型为Integer,那么这可行:

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

您唯一需要检查的是previous_node&amp; next_nodeNothing

答案 2 :(得分:0)

不,对象&#34;项目&#34;我不知道它在集合中的位置,所以它本身无法查找它。您最好的选择是创建自己的列表类型,并在需要重复使用时实现这些功能。

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