Interface IIterator<T>
An alternative interface to IEnumerator<T> that provides access to a sequence of elements.
Namespace: Recore.Collections.Generic
Assembly: Recore.dll
Syntax
public interface IIterator<out T>
Type Parameters
Name | Description |
---|---|
T |
Remarks
This interface is meant to resemble Java's concept of an iterator. While using IEnumerator<T> usually provides safer access to a collection than, say, manipulating indices directly in a list, there are times where it is clumsy to use.
Examples
A common case is calling an API that needs to tell its caller whether it should be called again. In order to do this with IEnumerator<T>, the API must look ahead to the next element with MoveNext() before returning and then maintain this state between calls.
For example, consider this type that gets status information on a customer's order from some external source:
using System.Collections.Generic;
class OrderStatusUpdater
{
private readonly IEnumerator<string> statusEnumerator;
private string currentStatus = null;
// We need to look ahead so we know when we've returned the last element
private string nextStatus = null;
private bool isFinished = false;
public OrderStatusUpdater(IEnumerable<string> statuses)
{
statusEnumerator = statuses.GetEnumerator();
UpdateStatus();
}
private void UpdateStatus()
{
currentStatus = nextStatus;
if (statusEnumerator.MoveNext())
{
nextStatus = statusEnumerator.Current;
}
else
{
isFinished = true;
}
}
public OrderStatus GetStatusUpdate()
{
UpdateStatus();
return new OrderStatus
{
Status = currentStatus,
IsFinished = isFinished
};
}
}
Now consider the code with IIterator<T>:
using System.Collections.Generic;
using Recore.Collections.Generic;
class OrderStatusUpdater
{
private readonly IIterator<string> statusIterator;
private string currentStatus = null;
public OrderStatusUpdater(IEnumerable<string> statuses)
{
statusIterator = Iterator.FromEnumerable(statuses);
}
public OrderStatus GetStatusUpdate()
{
if (statusIterator.HasNext)
{
currentStatus = statusIterator.Next();
}
return new OrderStatus
{
Status = currentStatus,
IsFinished = !statusIterator.HasNext
};
}
}
Properties
| Improve this Doc View SourceHasNext
Whether the sequence has more elements.
Declaration
bool HasNext { get; }
Property Value
Type | Description |
---|---|
Boolean |
Methods
| Improve this Doc View SourceNext()
Advances the iterator to the next element and returns it.
Declaration
T Next()
Returns
Type | Description |
---|---|
T |