如何从 VB.NET 的列表中找到对象的索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7750366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 15:43:36  来源:igfitidea点击:

How do I find the index of an object from a list in VB.NET?

vb.netlistindexingfind

提问by rokonoid

Say I have a list, and I have an object. How do I find the index of that object in the list?

假设我有一个列表,我有一个对象。如何在列表中找到该对象的索引?

回答by Tim Schmelter

You can use FindIndexto find the index of an object in a generic List: This is the most flexible method to get the index of an object.

您可以使用FindIndex在泛型 List 中查找对象的索引:这是获取对象索引的最灵活的方法。

 Dim list As New List(Of Object)
 Const myApple = "Apple111"
 For i = 0 To 1000
     List.Add("Apple" & i)
 Next
 Dim indexOfMyApple = list.FindIndex(Function(apple) myApple.Equals(apple)) 

But the IndexOfmethod is even simplier and more straightforward if you only want to find an object in a List by the DefaultEqualityComparer:

但是,如果您只想通过DefaultEqualityComparer在 List 中查找对象,则IndexOf方法甚至更简单、更直接:

Dim indexOfMyApple = list.IndexOf(myApple)

You can use IndexOfalso if you don't know what type it is, .NET will use Equalsto determine if two objects are equal(should be overridden to not only compare references).

IndexOf如果您不知道它是什么类型,您也可以使用,.NET 将使用Equals来确定两个对象是否相等(应该被覆盖以不仅比较引用)。