ForEach in un IEnumerable<T>
Linq è senza ombra di dubbio una delle features più belle introdotte da Microsoft in .NET negli ultimi anni (dopo i Generics); sicuramente anche gli Extension Methods hanno il loro fascino agevolando lo sviluppatore nella scrittura del codice. Purtroppo una cosa che mi manca in Linq (ma in realtà è un extension method) è il ForEach per IEnumerable<T>. In effetti c’è la possibilità di utilizzarlo per IList<T> e per le array, ma non per IEnumerable<T>.
Stufo di scrivere il foreach ogni volta, ho deciso di realizzarmi un’extension method che risolvesse il problema :).
Lo snippet seguente mostra la realizzazione:
/// <summary>
/// Eaches the specified enumeration.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="enumeration">The enumeration.</param>
/// <param name="action">The action.</param>
public static void ForEach <T> ( this IEnumerable <T> enumeration , Action <T> action )
{
Ensure.That ( enumeration ).IsNotNull ( );
foreach ( T item in enumeration )
action ( item );
}
Il suo UnitTest (sempre utilizzando SharpTestEx):
[TestMethod]
public void eachTest_with_null_object_shold_throw_argumentNullException()
{
var mockService = MockRepository.GenerateStrictMock<IFakeClass>();
ActionAssert.Throws<ArgumentNullException>(() => ((IEnumerable<string>)null).ForEach(x => mockService.FakeMethod("testValue")));
}
[TestMethod]
public void eachTest_with_valid_object()
{
IEnumerable<string> values = new List<string> { "testValue1", "testValue2", "testValue3" };
var mockService = MockRepository.GenerateStub <IFakeClass>();
values.ForEach(mockService.FakeMethod);
var calls = mockService.GetArgumentsForCallsMadeOn(obj => obj.FakeMethod(null));
calls [ 0 ] [ 0 ].Should ( ).Be.EqualTo ( "testValue1" );
calls [ 1 ] [ 0 ].Should ( ).Be.EqualTo ( "testValue2" );
calls [ 2 ] [ 0 ].Should ( ).Be.EqualTo ( "testValue3" );
}
Ciauz
The comments for this post are closed.
- There is no TrackBack for this post.
Archive