Mega Code Archive

 
Categories / C# / Collections Data Structure
 

Performs the specified action on each element of the IEnumerableT

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&lt;T&gt;.         /// </summary>         /// <typeparam name="T"></typeparam>         /// <param name="source">The source list of items.</param>         /// <param name="action">The System.Action&lt;T&gt; delegate to perform on each element of the IEnumerable&lt;T&gt;.</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&lt;T&gt;.         /// </summary>         /// <typeparam name="T"></typeparam>         /// <param name="source">The source list of items.</param>         /// <param name="action">The System.Action&lt;T&gt; delegate to perform on each element of the IEnumerable&lt;T&gt;.</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++;                 }         }     } }