I have a foreach loop and need to execute some logic when the last item is chosen from the List, e.g.:
foreach (Item result in Mod
Improving Daniel Wolf answer even further you could stack on another IEnumerable to avoid multiple iterations and lambdas such as:
var elements = new[] { "A", "B", "C" };
foreach (var e in elements.Detailed())
{
if (!e.IsLast) {
Console.WriteLine(e.Value);
} else {
Console.WriteLine("Last one: " + e.Value);
}
}
The extension method implementation:
public static class EnumerableExtensions {
public static IEnumerable> Detailed(this IEnumerable source)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
using (var enumerator = source.GetEnumerator())
{
bool isFirst = true;
bool hasNext = enumerator.MoveNext();
int index = 0;
while (hasNext)
{
T current = enumerator.Current;
hasNext = enumerator.MoveNext();
yield return new IterationElement(index, current, isFirst, !hasNext);
isFirst = false;
index++;
}
}
}
public struct IterationElement
{
public int Index { get; }
public bool IsFirst { get; }
public bool IsLast { get; }
public T Value { get; }
public IterationElement(int index, T value, bool isFirst, bool isLast)
{
Index = index;
IsFirst = isFirst;
IsLast = isLast;
Value = value;
}
}
}