Implementing a key/value pair collection...with a catch

  • Thread starter Thread starter Jeff L.
  • Start date Start date
J

Jeff L.

I have an interesting problem and I'm not coming up with any answers in my
searches, so hopefully someone can give me a hand with this. I have a
feeling it's easy, but I usually get my nose stuck too far in the details to
see the big picture. :)

I want to create a collection of key/value pairs. I have a class for the
key/value pair...we'll just call it KeyValuePair for this example. Now,
when creating the collection, I need to be able to have duplicate
keys...this is why I can't just use a hashtable. One more requirement is
that I can iterate through the entire collection, or just a subset of the
collection based on a key. The final requirement is that all key/value
pairs stay in the order that I added them...I can't have them rearranged
when I iterate through them. So, let's say the following is the data stored
in the collection:

Key Value
------------
AAA Test 1
BBB Test 2
AAA Test 3
BBB Test 4
AAA Test 5
CCC Test 6
DDD Test 7
EEE Test 8
EEE Test 9

I'd like to be able to do this:

For Each keyValuePair in keyValuePairCollection.Items
Debug.WriteLine("The key is " & keyValuePair.Key & " and the value is "
& keyValuePair.Value & ".")
keyValuePair.Value = keyValuePair.Value & " has been modified"
Debug.WriteLine("The new value is " & keyValuePair.Value & ".")
Next

The above code would iterate through all 9 key/value pairs and modify their
values. I'd also like to be able to do this:

For Each keyValuePair in KeyValuePairCollection.FilteredItems("AAA")
Debug.WriteLine("The key is " & keyValuePair.Key & " and the value is "
& keyValuePair.Value & ".")
keyValuePair.Value = keyValuePair.Value & " has been modified"
Debug.WriteLine("The new value is " & keyValuePair.Value & ".")
Next

The above code would iterate through only the 3 key/value pairs with a key
of "AAA" and modify their values. So...is all of this possible? Can anyone
send me in the right direction? I'd really appreciate any help you can
give. Thanks!
 
Hi,

Here is a suggestion. You store any type of data in a hashtable.
Why not store an arraylist with all of your values for each key.

Ken
 
I think I get what you're saying...the problem is that if I do it that way,
the key/value pairs will no longer be correctly ordered. I need to keep
them in their original order (which can be any order at all...no specific
sorting or anything). If I stick them into a hashtable based on their key
value, they won't be ordered correctly any more.

Jeff
 
One additional note...I forgot that you can't change a collection when you
enumerate through it. Ignore that part of my original message where I
showed code modifying the items as I iterated through with For Each. Read
only access should be enough for what I need to do.
 
Back
Top