ForEach extension that enumerates over all items in an and executes an action. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

ForEach extension that enumerates over all items in an and executes an action.

Demo Code


using System.Collections.Generic;
using System;/*  w  ww.ja v a 2s .  c o  m*/

public class Main{
        /// <summary>
        /// ForEach extension that enumerates over all items in an <see cref="IEnumerator{T}"/> and executes 
        /// an action.
        /// </summary>
        /// <typeparam name="T">The type that this extension is applicable for.</typeparam>
        /// <param name="collection">The enumerator instance that this extension operates on.</param>
        /// <param name="action">The action executed for each iten in the enumerable.</param>
        public static void ForEach<T>(this IEnumerator<T> collection, Action<T> action) {
            while (collection.MoveNext())
                action(collection.Current);
        }
        /// <summary>
        /// ForEach extension that enumerates over all items in an <see cref="IEnumerable{T}"/> and executes 
        /// an action.
        /// </summary>
        /// <typeparam name="T">The type that this extension is applicable for.</typeparam>
        /// <param name="collection">The enumerable instance that this extension operates on.</param>
        /// <param name="action">The action executed for each iten in the enumerable.</param>
        public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action) {
            foreach (var item in collection)
                action(item);
        }
}

Related Tutorials