Nov 06

C#, LINQ and running several methods over instances of a collection

Posted in C#      Comments Off on C#, LINQ and running several methods over instances of a collection

One of the things that I’ve needed to do in the past is filter a sequence of items and then execute a specific method over each of those filtered instances. The Enumerable class introduces several methods, but it doesn’t have any that lets me pass an Action<T> that is invoked over each instance of an IEnumerable<T>. So, what you tipically end up doing is something like this:

var filteredItems = existingItems.Where( item => … );
foreach( var item in filteredItems ){

Yes, there’s nothing wrong with this code, but it starts getting boring when you have to write it 2 or 3 times. Interestingly, the List<T> class already has a method similar to what we need: the ForEach method. Here’s its signature:

public void ForEach(Action<T> action)

So, I could end up converting to a list (by calling the Enumerable.ToList<T> method) and then I could simply call this ForEach method. Here’s how it would look like:

existingItems.Where( item => … )
                     .ForEach( item => item.DoSomething() );

Another option would be to add a new extension method  that looks like this:

public static class MyEnumerable{
   public static void ForEach<T>(this IEnumerable<T> items,
                                                                      Action<T> action){
      if( action == null ) throw

Then I could simply do something like this:

existingItems.Where( item => … )
                      .ForEach( item => item.DoSomething() );

I’ve tried to understand why Enumerable didn’t add this method. I’ve found some good arguments (for instance, it could be confusion when passing a List – in this case, the List<T>.ForEach method would always be called, but that might not be obvious to all the developers-, maintaining functional purity,etc),but I still think that having it on the list wouldn’t have been such a bad thing (ok, you’d have side effects, but C# isn’t a functional language, right?).

My friend Paulo reminds me that with a list you have an internal store, so it makes sense to have that method and access the internal array used for saving the members of the list directly. If you think about it, then it probably doesn’t make much sense to add a method like that because you’re extending the IEnumerable<T> and don’t have any info on how the items are stored.

On the other hand, if you think about certain scenarios, then it does make sense to go over a collection of items and call a specific method when an instance is in a specific state (that’s something similar to the example I’ve shown in the beginning of this post).

Btw, if you have a good justification for why this method wasn’t added to the Enumerable class (besides the one I’ve written in the previous paragraphs), go ahead and add it to the comments section. I’d really love to know more 🙂