-1

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.

user3103858
  • 23
  • 1
  • 2
  • Side note: HashSet is not ordered in any sense, so picking n-th element as good as first one... Do you really need indexed access to HashSet? – Alexei Levenkov Dec 15 '13 at 07:26
  • If you want O(1) access to an element in an ordered collection by index, any reason not to use `List`? – Baldrick Dec 15 '13 at 07:27

1 Answers1

2

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.

Community
  • 1
  • 1
Baldrick
  • 11,712
  • 2
  • 31
  • 35