1 Replies - 280 Views - Last Post: 14 July 2014 - 03:11 AM Rate Topic: -----

#1 davrow  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 13-July 14

Class Array Search using IndexOf

Posted 14 July 2014 - 12:14 AM

Hi there, I'm using VB.NET (VS 2008) and I have question about searching an array of objects.
All the examples I've seen have been for simple string or numeric arrays when using the IndexOf
search function but I'm having trouble getting it to work for an array of objects. As an example
(see below) I have a person class with three properties FirstName (string), Surname (string), Age(integer)
If I try to retrieve the age of the person call "Joe" by searching for the associated index
using the firstname, I get -1 returned. Is this the correct way to do a search on class arrays
or is there a better method ?

Thanks for any help,
Dave

public class person
  Public FirstName as string
  Public Surname as string
  Public Age as integer
end class

dim people(9) as person
for i = 0 to 9
   people(i) = new person
next i

'populate the array ... then do a search

dim idx = array.indexof(people,"Joe")
'idx returns as -1

This post has been edited by andrewsw: 14 July 2014 - 03:02 AM
Reason for edit:: Added CODE tags


Is This A Good Question/Topic? 0
  • +

Replies To: Class Array Search using IndexOf

#2 andrewsw  Icon User is offline

  • It's just been revoked!
  • member icon

Reputation: 3624
  • View blog
  • Posts: 12,527
  • Joined: 12-December 12

Re: Class Array Search using IndexOf

Posted 14 July 2014 - 03:11 AM

That won't work, it won't look within the object's properties. (It is probably looking at a string-version of the object, just a cryptic code-number.)

You can use a lambda to do this:
Dim idx = Array.FindIndex(people, Function(p As Person) p.FirstName = "Joe")

I am trusting you to study why and how this works.

This post has been edited by andrewsw: 14 July 2014 - 03:18 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1