Is there a class like Dictionary<> in C#, but for just keys, no values?

16,485

Try using the HashSet<T> class.

Edit: I spent a long long time doing exactly what you did until I just stumbled on this class while reading a blog.

Share:
16,485
Chuck Wilbur
Author by

Chuck Wilbur

Currently a DevOps engineer in AWS (Jenkins, jx, CDK, CloudFormation) Coded in C++ on AutoCAD's ARX API from 1998-2010. Some experience using VBA, XML, javascript and C#

Updated on June 27, 2022

Comments

  • Chuck Wilbur
    Chuck Wilbur almost 2 years

    I guess another way to phrase this would be "Is there a class like List<> in C#, but optimized for checking whether a particular value is present?" I'm sure for a small set of values List<>.Contains would probably be fine, but what if I have a set of thousands or millions of values and wanted to find out whether a certain value was in it?

    I've implemented this kind of thing in the past by creating a Dictionary<object, int> and setting the value to 0 for every key, but this feels really clunky. And now there's Stack Overflow, where my stupid question can be transformed into education for thousands (dozens, even). So here it is!

    I'm not even sure what such a class would be called, other than maybe Set, so obviously searches on the topic have been... challenging :)

  • R. Martinho Fernandes
    R. Martinho Fernandes about 14 years
    Also, in .NET 4, this class now implements the new ISet<T> interface, along with its also-new cousin SortedSet<T>, which is the same, but with order semantics.
  • jjxtra
    jjxtra about 14 years
    Back in the dark days of .NET 1.0 and 2.0 we just made a class that essentially worked like HashSet but used a dictionary of <TKey, byte> underneath.
  • Ryan Emerle
    Ryan Emerle about 14 years
    @Jeff same here, though we used <T,bool>
  • R. Martinho Fernandes
    R. Martinho Fernandes about 14 years
    @Jeff: you just made me feel nostalgic. I'm not sure that's a good thing.
  • Aaronaught
    Aaronaught about 14 years
    In the .NET 2.0 days I just used the PowerCollections library which already had a Set<T>, Bag<T>, and ordered variants... pretty much everything that MS finally got around to including in .NET 4. I thought everybody knew about it. :P
  • yfeldblum
    yfeldblum about 14 years
    The Iesi.Collections library ships with NHibernate. It includes implementations of ISet<T> etc.
  • Larry
    Larry over 8 years
    I accidentally build a Dictionary<object, object>()
  • Douglas Gaskell
    Douglas Gaskell almost 5 years
    Note that you can't access a HashSet indexer like a Dictionary. Say your key is a string, you can't do myHash["mykey"] where in a dictionary you can.