Last active
January 15, 2021 07:34
-
-
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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