Created
August 2, 2011 18:16
-
-
Save damianh/1120821 to your computer and use it in GitHub Desktop.
IEnumerable ForEach safety extensions
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
namespace System.Collections.Generic | |
{ | |
using System.Linq; | |
public static class IEnumerableExtensions | |
{ | |
// Why ForEach extension is not included on IEnumerable<T> by default http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx | |
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) | |
{ | |
Guard.Against(action == null, new ArgumentNullException("action")); | |
if(source == null) return; | |
foreach (T t in source) | |
{ | |
action(t); | |
} | |
} | |
public static void ForEachSkipNull<T>(this IEnumerable<T> source, Action<T> action) | |
{ | |
Guard.Against(action == null, new ArgumentNullException("action")); | |
if(source == null) return; | |
foreach (T t in source.Where(t => !ReferenceEquals(t, null))) | |
{ | |
action(t); | |
} | |
} | |
public static void ForEachThrowOnNull<T>(this IEnumerable<T> source, Action<T> action) | |
{ | |
Guard.Against(action == null, new ArgumentNullException("action")); | |
if(source == null) return; | |
foreach (T t in source) | |
{ | |
if (ReferenceEquals(t, null)) | |
{ | |
throw new InvalidOperationException("Item is null"); | |
} | |
action(t); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment