Created
May 24, 2012 13:06
-
-
Save hickford/2781446 to your computer and use it in GitHub Desktop.
C# foreach loop with different action for final item
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
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