Skip to content

Instantly share code, notes, and snippets.

@yumaikas
Last active January 15, 2021 07:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yumaikas/71c9c35a85484f49484350cff8dd1c6e to your computer and use it in GitHub Desktop.
Save yumaikas/71c9c35a85484f49484350cff8dd1c6e to your computer and use it in GitHub Desktop.
Shows if you're at the start, middle, or end of a foreach loop in C#
// This code assumes that it's run as a LinqPad script, but it's just the Main() part that assumes that.
void Main()
{
LoopStatus(new int[]{ 1, 2, 3, 4, 5 }).Dump();
}
// Define other methods and classes here
public enum Iteration {
First,
Middle,
Last,
}
public struct IterationPostition<T> {
public Iteration Iteration {get; private set;}
public T Value {get; private set;}
public IterationPostition(Iteration iter, T value)
{
Value = value;
Iteration = iter;
}
}
public IEnumerable<IterationPostition<T>> LoopStatus<T>(IEnumerable<T> innerIterator) {
var enumerator = innerIterator.GetEnumerator();
bool hasMoreItems = false;
T prev = default(T);
Iteration state = Iteration.First;
while (true)
{
switch (state) {
case Iteration.First:
hasMoreItems = enumerator.MoveNext();
yield return new IterationPostition<T>(Iteration.First, enumerator.Current);
hasMoreItems = enumerator.MoveNext();
prev = enumerator.Current;
state = Iteration.Middle;
break;
case Iteration.Middle:
hasMoreItems = enumerator.MoveNext();
if (hasMoreItems) {
yield return new IterationPostition<T>(Iteration.Middle, prev);
prev = enumerator.Current;
} else {
yield return new IterationPostition<T>(Iteration.Last, prev);
state = Iteration.Last;
}
break;
case Iteration.Last:
yield break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment