Skip to content

Instantly share code, notes, and snippets.

@hickford
Created May 24, 2012 13:06
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 hickford/2781446 to your computer and use it in GitHub Desktop.
Save hickford/2781446 to your computer and use it in GitHub Desktop.
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