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
2009-09-01 17:55:44
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
2009-09-01 18:00:56
Another approach in .NET 2.0 is to use `KeyedCollection`, and define the key extractor method as value identity.
Pavel Minaev
2009-09-01 18:01:28
more info on using hashset: http://bit.ly/1FYcf
p.campbell
2009-09-01 18:02:04
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
2009-09-01 18:20:27
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
2009-09-01 18:25:28
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
2009-09-01 18:31:19
+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
2009-09-01 18:00:34
+1
A:
If you're not targeting .NET 3.5, Power Collections (open source) also provides a Set implementation.
Eric J.
2009-09-01 18:18:06