15

Possible Duplicate:
Why can't I retrieve an item from a HashSet without enumeration?

I need to add a lot of objects to a Set.and I should retrieve them very fast. The only way that I know is using hash. But the HashSet class in C# doesn't contain any 'Get' method. The dictionary class isn't useful because Finding an object is very time-consuming in a dictionary.

Community
  • 1
  • 1
Masoud
  • 1,354
  • 6
  • 18
  • 30

2 Answers2

14

HashSets are basically used to test if an object is included in the collection. It is un-orderd and un-sorted, doesnt have an index that could be used to retrive an object.

If you need to store and retrieve objects, use other collection types like List, HashTable etc.

Danish Khan
  • 1,893
  • 5
  • 22
  • 35
  • I am sorry, I dont understand. Here is how you can use a HashTable. http://support.microsoft.com/kb/309357 – Danish Khan Jan 06 '11 at 11:05
  • There is a Hashtable class in System.Collections.Hashtable. http://msdn.microsoft.com/es-es/library/system.collections.hashtable.aspx – Devendra D. Chavan Jan 06 '11 at 11:05
  • The (generic) hashtable class is called `Dictionary`. – CodesInChaos Jan 06 '11 at 11:07
  • 1
    hashtable hsa no get method same as hashset. dictionary is too slow. I need a real hash that can retrieve added datas very fast. – Masoud Jan 06 '11 at 11:10
  • @Masoud I would recommend that you share the exact scenario that you want to implement. That way we would be able to help you better. – Danish Khan Jan 06 '11 at 11:12
  • You can store your data in the keys of a Dictionary. The values can be anything (don't care). For example booleans which are all 'true'. Finding your data will then be quick - O(1). – oferei Dec 07 '16 at 10:38
  • @oferei that does not work as there is still no way to access the existing Dictionary key using your 'equivalent' key. You need to use a Dictionary where the key and value are the same. – Andrew Hanlon Jan 25 '17 at 18:55
1

The HashSet represents a number of values. You can look if a certain value is in the set by using Contains(). A Dictionary is for storing objects and retrieving it by its hash (key).

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        public enum EnumA
        {
            One,
            Two,
            Three,
            Four
        }

        static void Main(string[] args)
        {
            HashSet<EnumA> test = new HashSet<EnumA>();

            test.Add(EnumA.Four);

            Console.WriteLine("Contains one:");
            Console.WriteLine(test.Contains(EnumA.One));
            Console.WriteLine("Contains four:");
            Console.WriteLine(test.Contains(EnumA.Four));
            Console.WriteLine();
            Console.ReadLine();

            return;
        }
    }
}
Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203