Search code examples
javac#iteratorsequences

Write remove method at index based on iterator equivalent from java to c#


I am trying to write the equivalent method from java. MyIterator extends Iterator.

public T remove(int index) {
    MyIterator<T> it = support.iterator();//returns iterator over my sequence implementation
    int i = 0;
    T e = null;
    while (it.hasNext() && i < index) {
        e = it.next();
        i++;
    }
    it.remove();
    return e;
}

How can I write this to c# since there is no defined method for it.remove?


Solution

  • C#/.Net iterators (IEnumerator<T> as returned by IEnumerable<T> ) are read-only forward only iterators and do not allow removing items from underlying collection compared to Java's iterator.remove.

    Most collections support removing items by index like List<T>.RemoveAt which would be close equivalent.

    Alternatively if you just want to skip item during iteration - Enumarable.Skip or Enumerable.Where can be an option:

       mySequence.Where((item,id) => id != indexToSkip)