Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 201
rokonoid Avatar asked Oct 13 '11 06:10

rokonoid


People also ask

What is the value of the index for the first element in a VB.NET array?

The first position for arrays in VB.NET is zero; same rules apply to any in-built collection/function requiring indexing and to other .

How do you get the index of an item in a list C#?

To get the index of an item in a single line, use the FindIndex() and Contains() method. int index = myList. FindIndex(a => a.

How do I add an item to a list in Visual Basic?

To add items to a ListBox, select the ListBox control and get to the properties window, for the properties of this control. Click the ellipses (...) button next to the Items property. This opens the String Collection Editor dialog box, where you can enter the values one at a line.

What is list in Visual Basic?

The list is designed to support the topic Walkthrough: Writing Queries in Visual Basic. It also can be used for any application that requires a list of objects. The code defines the items in the list of students by using object initializers.


1 Answers

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

 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 IndexOf method is even simplier and more straightforward if you only want to find an object in a List by the DefaultEqualityComparer:

Dim indexOfMyApple = list.IndexOf(myApple)

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

like image 184
Tim Schmelter Avatar answered Oct 16 '22 16:10

Tim Schmelter