Dictionary with keys only. Anything ?

  • Thread starter Thread starter pamela fluente
  • Start date Start date
P

pamela fluente

Sometimes I define a
System.Collections.Generic.Dictionary(Of Key, ...)

but actually I only use the Key part. Is there any collection which I
can use
which is similar to a Dictionary, but without the value part ?
I mean just a list of unique key Object , with a O(1) retrieval
operation ?

-Pam
 
All collections have value parts. If your keys are strings, use
System.Collections.Specialized.StringCollection. Otherwise, try

dim Valueless as new Dictionary(of KeyType, KeyType)
Valueless.add(key, key)

At least this way you don't have two objects floating around memory - just
one with two references.

Mike Ober.
 
Sometimes I define a
System.Collections.Generic.Dictionary(Of Key, ...)

but actually I only use the Key part. Is there any collection which I
can use
which is similar to a Dictionary, but without the value part ?
I mean just a list of unique key Object , with a O(1) retrieval
operation ?

-Pam

I'm particularly fond of
System.Collections.ObjectModel.KeyedCollection(Of Key, Item). It's
usefull when the item is also the key, or the key is a property of the
item itself. Unfortunately its an abstract class, which means you must
inherit it, because there's a GetKeyForItem method that needs
implementation. Indexed access is O(1), while keyed access is near
O(1) -- or so the docs say. Besides, it has the definite advantage (to
me) that it keeps the insertion order (which a Dictionary won't).

HTH.

Regards,

Branco.
 
All collections have value parts. If your keys are strings, use
System.Collections.Specialized.StringCollection.

The times I need keys only are often those where the object is also
used as a key (through an appropriate comparer).

Otherwise, try
dim Valueless as new Dictionary(of KeyType, KeyType)
Valueless.add(key, key)

Yes that's what I am doing. Or else I do Valueless.add(key, Nothing)
(is this better?) which anyway seems quite awkward to me.
 
I'm particularly fond of
System.Collections.ObjectModel.KeyedCollection(Of Key, Item). It's
usefull when the item is also the key, or the key is a property of the
item itself. Unfortunately its an abstract class, which means you must
inherit it, because there's a GetKeyForItem method that needs
implementation. Indexed access is O(1), while keyed access is near
O(1) -- or so the docs say. Besides, it has the definite advantage (to
me) that it keeps the insertion order (which a Dictionary won't).

Hmm I might give it a try. Isn't strange that there isn't a collection
of keys only ? I think it could be nice to have it
 
Back
Top