Generic collection question

  • Thread starter Thread starter SStory
  • Start date Start date
S

SStory

I am doing a Generic.Dictionary(of string,myobject)

I need to access the item by key, but also by index. Is this the wrong thing
to use? Should I be using something different.

In other words sometimes I just need item(0), the first item added to the
list, but other times by key.

TIA,

Shane
 
To access the keys by index, use the following code:

Dim KeyArray(YourDictionary.Keys.Count) as string
YourDictionary.Keys.CopyTo(KeyArray)

ValueByIndex = YourDictionary(KeyArray(Index))
 
Well,

I was reading the documentation which says there is no way to guarantee the
order.
I need item 0.

I am now trying to build my own generic class to do this.

Thanks,

Shane
 
I just runned some tests, and it seems that the order stays in the order
you added the items, as long as you don't use the remove method.
 
That's what I did and finally got it going.

For any who read this.. BE WARE that For Each doesn't work well with it
unless you override the GetEnumerator and return the values.GetEnumerator

This will make it work as you would expect. Otherwise you get an
enumeration of the keys.

Thanks to all!

Shane
 
SStory,
If I need a generic collection with access by key & index I will normally
use a System.Collections.ObjectModel.KeyedCollection(Of TKey, TItem).
Especially when used as a base class.

--
Hope this helps
Jay B. Harlow [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net


|I am doing a Generic.Dictionary(of string,myobject)
|
| I need to access the item by key, but also by index. Is this the wrong
thing
| to use? Should I be using something different.
|
| In other words sometimes I just need item(0), the first item added to the
| list, but other times by key.
|
| TIA,
|
| Shane
|
|
 
Back
Top