Question

I write a code, but I need it to work faster, not in O(n).

    public T GetElementAt(int index)
    {        
        return hashSet.ElementAt(index);
    }

and another one

    public T GetElementAt(int index)
    {
        var enumerator = hashset.GetEnumerator();
        for (int i = 0; i < index; i++)
        {
            enumerator.MoveNext();
        }
        return enumerator.Current;
    }

Please, help me, I have no idea how to do this.

P.S. Sorry for my bad English.

Was it helpful?

Solution

It looks like you might be using HashSet<T> for the wrong purpose.

Sets are designed for:

  1. Ensuring uniqueness
  2. The ability to extract all members when needed
  3. Checking whether a supplied item is already a member

HashSet<T> does the above things, and it does them very fast. But that's pretty much all it does.

Sets are not ordered, so trying to get the nth value doesn't really have any meaning or use.

For what you're doing (O(1) access by numbered item offset), List<T> will do perfectly well.

This answer here gives a more detailed description of what HashSet<T> is for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top