代码之家  ›  专栏  ›  技术社区  ›  ariel

vb.net:“for each”中的索引号

  •  15
  • ariel  · 技术社区  · 15 年前

    在VB.net中,我有时会遇到这样的情况:

    For Each El in Collection
       Write(El)
    Next
    

    For I = 0 To Collection.Count() - 1
       Write(I & " = " & Collection(I))
    Next
    

    甚至(更糟)

    I = 0
    For Each El In Collection
       Write(I & " = " & El)
       I += 1
    Next
    

    有没有其他方法来获取索引?

    3 回复  |  直到 15 年前
        1
  •  29
  •   Jim Counts    15 年前

    IndexOf method .

    For Each El in Collection
       Write(Collection.IndexOf(El) & " = " & El)
    Next
    
        2
  •  11
  •   Mark Entingh    10 年前

    Dim i as Integer = 0
    For Each obj In myList
        'Do stuff
        i+=1
    Next
    
        3
  •  4
  •   Ahmad Mageed    15 年前

    如果您需要索引,那么for循环是最直接的选项,并且具有很好的性能。除了你提到的备选方案之外,你还可以使用 Select

    Dim list = Enumerable.Range(1, 10).Reverse() ''# sample list
    Dim query = list.Select(Function(item, index) _
                               New With { .Index = index, .Item = item })
    For Each obj In query
        Console.WriteLine("Index: {0} -- Item: {1}", obj.Index, obj.Item)
    Next