How to implement For...Each on my Classes

  • Thread starter Thread starter Ale K.
  • Start date Start date
A

Ale K.

Hi, i need some help with the following thing....
i got two classes , PersonData, and PersonDataCollection that inherits from
DictionaryBase for been able to store PersonData Items, the thing is that i
want to be able to implement FOR....EACH with this classes.
How can i do this??

Thanks.
Alex.

(Quick And Dirty Example of what i want)
.....On A Form....
Dim PersonCollection as New PersonDataCollection

Public Sub ListPersons()
Dim dp as PersonData
FillCollection()' Imaginary Function Filling PersonCollection Object
For each dp on PersonCollection
messagebox.show(dp.name)
next
End Sub


Public Class PersonData
Public Name as String
End Class

Public Class PersonDataCollection
Inherits DictionaryBase
ReadOnly Property Item(ByVal Id As Long) As PersonData
Get
Return CType(dictionary.Item(Id.ToString), PersonData)
End Get
End Property
End Class
 
I'm not sure what your asking for, is this it ?

Dim PC as New PersonDataCollection

For Each PC in Dim PersonCollection
'do stuff

Next
 
ARHHHHHHHH!!!

Dim PersonCollection as New PersonDataCollection

'Add Stuff to Personal Collection

Dim PD as PersonData

For Each PD in PersonCollection

' Do Stuff

Next
 
Alex,
DictionaryBase already implements For Each for you!

Because it is a Dictionary it implements the
System.Collections.IDictionaryEnumerator interface, instead of
System.Collections.IEnumerator.

You can code your for each something like:

Dim de As DictionaryEntry
Dim PersonCollection as New PersonDataCollection
Dim dp as PersonData

For each de on PersonCollection
dp = DirectCast(de.Value, PersonData)
messagebox.show(dp.name)
Next

To get your code to work, you can Shadow the GetEnumerator method and return
InnerHashtable.Values.GetEnumerator instead. If you search this newsgroup at
groups.google.com there may be an example of shadowing GetEnumerator.

I simply use the DictionaryEntry as above, as it gives you both the key &
value at the same time. (I don't bother shadowing GetEnumerator).

Hope this helps
Jay
 
Ale K. said:
Hi, i need some help with the following thing....
i got two classes , PersonData, and PersonDataCollection that
inherits from DictionaryBase for been able to store PersonData Items,
the thing is that i want to be able to implement FOR....EACH with
this classes. How can i do this??

DictionaryBase already implements IEnumerable - it is necessary to be used
for being used with for..each - so it should already work.
 
Back
Top