Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C# foreach loop with different action for final item
public static class EnumerableExtensions
{
/// <summary>
/// Perform an action on each element of an IEnumerable<T>, optionally specifying a different action for the final item.
/// </summary>
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action, Action<T> finalAction=null)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (action == null)
{
throw new ArgumentNullException("action");
}
finalAction = finalAction ?? action;
using(var iter = source.GetEnumerator())
{
if(iter.MoveNext())
{
T item = iter.Current;
while(iter.MoveNext())
{
action(item);
item = iter.Current;
}
finalAction(item);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.