views:

447

answers:

4

Is there any data structure in C# that is like a dictionary but that only has a key and doesn't have a value. I basically want a list of integers that I can quickly lookup and see if a certain value is in the list. Granted, for my current use, a List would not cause any performance problem, but it just doesn't seem to fit well with the intent of what my code is doing.

+16  A: 

Yes, it's called a HashSet<T>, and available in version 3.5 of the .NET framework. If you use .NET version 2.0, you can use a Dictionary and set values to null.

Meta-Knight
Note that Hashset<T> was introduced in .NET Framework 3.5. If you're on an earlier version, I guess using a Dictionary<int, object> and set all the values to null.
codeape
Another approach in .NET 2.0 is to use `KeyedCollection`, and define the key extractor method as value identity.
Pavel Minaev
more info on using hashset: http://bit.ly/1FYcf
p.campbell
Awesome, I didn't even know about this, I always made a Dictionary<TKey, bool> and just set bool to true, and I always felt dirty when I did it
Paul Betts
An interesting point about "HashSet" -- why "HashSet"? That is, why mention an *implementation detail* of the class -- that it implements set semantics with a hash table -- in the name of the class? The answer: because "Set" is a keyword of Visual Basic, meaning that in VB, any time you'd use one, you'd have to say Dim MySet as [Set] -- yuck. That's *extremely* error prone; better to have a sub-optimal name than to produce confusing errors.
Eric Lippert
Thanks for the info, Eric. There was a discussion about this in the web page referenced by pcampbell, but it's good to hear a confirmation :-)
Meta-Knight
A: 

or use a SortedList where values have to be unique

Gregoire
+4  A: 

If 3.5 is not an option you could do something like Dictionary < int, int > and simply ignore the value. i've done this in 2.0 and i tend to set the value to the same as the key.

Paul Sasik
+1  A: 

If you're not targeting .NET 3.5, Power Collections (open source) also provides a Set implementation.

Eric J.