Skip to content

Instantly share code, notes, and snippets.

@panesofglass
Created November 5, 2009 16:22
Show Gist options
  • Save panesofglass/227172 to your computer and use it in GitHub Desktop.
Save panesofglass/227172 to your computer and use it in GitHub Desktop.
ForEach extensions
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Foundation.Collections
{
/// <summary>
/// Adds extension methods to the IEnumerable{T} interface.
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// Performs an action on the specified collection.
/// </summary>
/// <param name="collection">The collection.</param>
/// <param name="action">The action.</param>
/// <remarks>
/// <para>
/// Use the ForEach method to perform an action on a collection
/// of items, one at a time, as you would when using a foreach loop.
/// </para>
/// <para>
/// <example>
/// <code>
/// IEnumerable collection = new string[] {"a", "b", "c"};
/// collection.ForEach(Console.WriteLine);
/// </code>
/// produces the following output:
/// <code>
/// a
/// b
/// c
/// </code>
/// </example>
/// </para>
/// </remarks>
public static void ForEach(this IEnumerable collection, Action<object> action)
{
foreach (var item in collection)
{
action(item);
}
}
/// <summary>
/// Performs an action on the specified collection.
/// </summary>
/// <param name="collection">The collection.</param>
/// <param name="action">The action.</param>
/// <remarks>
/// <para>
/// Use the ForEachWithIndex method to perform an action on a collection
/// of items, one at a time, as you would when using a foreach loop.
/// This method allows the action to consider an index, as well.
/// </para>
/// <para>
/// <example>
/// <code>
/// IEnumerable collection = new string[] {"a", "b", "c"};
/// collection.ForEachWithIndex(Console.WriteLine);
/// </code>
/// produces the following output:
/// <code>
/// a
/// b
/// c
/// </code>
/// </example>
/// </para>
/// </remarks>
public static void ForEachWithIndex(this IEnumerable collection, Action<object, int> action)
{
int i = 0;
foreach (var item in collection)
{
action(item, i++);
}
}
/// <summary>
/// Performs an action on the specified collection.
/// </summary>
/// <typeparam name="T">The type contained in the generic collection.</typeparam>
/// <param name="collection">The collection.</param>
/// <param name="action">The action.</param>
/// <remarks>
/// <para>
/// Use the ForEach{T} method to perform an action on a collection
/// of items, one at a time, as you would when using a foreach loop.
/// </para>
/// <para>
/// <example>
/// <code>
/// IEnumerable{string} collection = new string[] {"a", "b", "c"};
/// collection.ForEach(Console.WriteLine);
/// </code>
/// produces the following output:
/// <code>
/// a
/// b
/// c
/// </code>
/// </example>
/// </para>
/// </remarks>
public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
{
T[] items = collection.ToArray();
int count = items.Count();
for (int i = 0; i < count; i++)
{
if (items[i] == null)
{
throw new NullReferenceException("The value of the item cannot be null.");
}
action(items[i]);
}
}
/// <summary>
/// Performs an action on the specified collection.
/// </summary>
/// <typeparam name="T">The type contained in the generic collection.</typeparam>
/// <param name="collection">The collection.</param>
/// <param name="action">The action.</param>
/// <remarks>
/// <para>
/// Use the ForEachWithIndex{T} method to perform an action on a collection
/// of items, one at a time, as you would when using a foreach loop.
/// This method allows the action to consider an index, as well.
/// </para>
/// <para>
/// <example>
/// <code>
/// IEnumerable{string} collection = new string[] {"a", "b", "c"};
/// collection.ForEachWithIndex(Console.WriteLine);
/// </code>
/// produces the following output:
/// <code>
/// a
/// b
/// c
/// </code>
/// </example>
/// </para>
/// </remarks>
public static void ForEachWithIndex<T>(this IEnumerable<T> collection, Action<T, int> action)
{
T[] items = collection.ToArray();
int count = items.Count();
for (int i = 0; i < count; i++)
{
action(items[i], i);
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Foundation.Collections;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Foundation.Test.Collections
{
/// <summary>
///This is a test class for EnumerableExtensionsTest and is intended
///to contain all EnumerableExtensionsTest Unit Tests
///</summary>
[TestClass]
public class EnumerableExtensionsTest
{
#region properties
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext { get; set; }
/// <summary>
/// Gets or sets the collection.
/// </summary>
/// <value>The collection.</value>
private IEnumerable Collection { get; set; }
/// <summary>
/// Gets or sets the generic collection.
/// </summary>
/// <value>The generic collection.</value>
private IEnumerable<string> GenericCollection { get; set; }
/// <summary>
/// Gets or sets the string builder.
/// </summary>
/// <value>The string builder.</value>
private StringBuilder Sb { get; set; }
#endregion
#region methods
/// <summary>
/// Use TestInitialize to run code before running each test
/// </summary>
[TestInitialize]
public void MyTestInitialize()
{
// For the record, this is one of the earliest set of tests I wrote.
// Just sayin'.
Sb = new StringBuilder();
Collection = new[] {"a", "b", "c"};
GenericCollection = new List<string> {"a", "b", "c"};
}
/// <summary>
/// A test for ForEach{T}
/// </summary>
[TestMethod]
public void ForEachGenericTest()
{
GenericCollection.ForEach(i => Sb.Append(i));
Assert.AreEqual("abc", Sb.ToString());
}
/// <summary>
/// A test for ForEach
/// </summary>
[TestMethod]
public void ForEachTest()
{
Collection.ForEach(i => Sb.Append(i.ToString()));
Assert.AreEqual("abc", Sb.ToString());
}
/// <summary>
/// A test for ForEachWithIndex{T}
/// </summary>
[TestMethod]
public void ForEachWithIndexGenericTest()
{
GenericCollection.ForEachWithIndex((s, i) => Sb.Append(string.Format("{0}: {1}, ", i, s)));
Assert.AreEqual("0: a, 1: b, 2: c, ", Sb.ToString());
}
/// <summary>
/// A test for ForEachWithIndex
/// </summary>
[TestMethod]
public void ForEachWithIndexTest()
{
GenericCollection.ForEachWithIndex((s, i) => Sb.Append(string.Format("{0}: {1}, ", i, s)));
Assert.AreEqual("0: a, 1: b, 2: c, ", Sb.ToString());
}
/// <summary>
/// A test to ensure that the IEnumerable ForEach extension method
/// does not break the List ForEach() method.
/// </summary>
[TestMethod]
public void ForEachTest_DoesNotBreakListForEach()
{
List<string> list = GenericCollection.ToList();
list.ForEach(i => Sb.Append(i));
Assert.AreEqual("abc", Sb.ToString());
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment