Performs the specified action on each element of the IEnumerable
using System.Linq;
using System.Diagnostics;
namespace System.Collections.Generic
{
public static class EnumeratorExtensions
{
/// <summary>
/// Performs the specified action on each element of the IEnumerable<T>.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source list of items.</param>
/// <param name="action">The System.Action<T> delegate to perform on each element of the IEnumerable<T>.</param>
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null)
throw new ArgumentNullException("source");
if (action == null)
throw new ArgumentNullException("action");
using (IEnumerator<T> data = source.GetEnumerator())
while (data.MoveNext())
{
action(data.Current);
}
}
/// <summary>
/// Performs the specified action on each element of the IEnumerable<T>.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source list of items.</param>
/// <param name="action">The System.Action<T> delegate to perform on each element of the IEnumerable<T>.</param>
public static void ForEach<T>(this IEnumerable<T> source, Action<T, int> action)
{
if (source == null)
throw new ArgumentNullException("source");
if (action == null)
throw new ArgumentNullException("action");
int index = 0;
using (IEnumerator<T> data = source.GetEnumerator())
while (data.MoveNext())
{
action(data.Current, index);
index++;
}
}
}
}
Related examples in the same category