如何在 For Each...Next 循环中获取对象的索引? [英] How do I get the index of an object in a For Each...Next loop?

查看:55
本文介绍了如何在 For Each...Next 循环中获取对象的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下语法循环遍历列表集合:

I'm using the following syntax to loop through a list collection:

For Each PropertyActor As JCPropertyActor In MyProperty.PropertyActors

    i = IndexOf(PropertyActor)
Next

如何在循环中获取当前对象的索引?我正在使用 IndexOf(PropertyActor) 但这似乎效率低下,因为它在我已经拥有可用对象时搜索集合!

How do I get the index of the current object within the loop? I'm using IndexOf(PropertyActor) but this seems inefficient as it searches the collection when I already have the object available!

推荐答案

索引对 IEnumerable 没有任何意义,而这正是 foreach 构造所使用的.这很重要,因为 foreach 可能不会按索引顺序枚举,如果您的特定集合类型以一种奇怪的方式实现 IEnumerable.如果您有一个可以通过索引访问的对象并且您在迭代期间关心索引,那么您最好只使用传统的 for 循环:

An index doesn't have any meaning to an IEnumerable, which is what the foreach construct uses. That's important because foreach may not enumerate in index order, if your particular collection type implements IEnumerable in an odd way. If you have an object that can be accessed by index and you care about the index during an iteration, then you're better off just using a traditional for loop:

for (int i=0;i<MyProperty.PropertyActors.Length;i++)
{
    //...
}

这篇关于如何在 For Each...Next 循环中获取对象的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆