Using the ForEach Method


Introduction

I’ve found a new “toy” in the C# language this week, the Foreach extension method. It seems to me to be a very effective way of expressing some of those short “iterate over an x and do something to the members.

I’ve always been a bit “frustrated” with C# when it comes to iterating over collections. The foreach syntax is fine, when you’re doing a loop which has some complex logic. But, for short sharp thing, has always seemed to be a few too many keystrokes for the results. Sure, there is the code snippet for foreach which cuts down the keystrokes, but you still have the minimum of 2 lines of code, or 4 if you us { and }. Also my “inbuilt style guide” baulks at putting multiple statements on one line.

foreach (string part in TransactionTriggers) Debug.WriteLine(String.Format(" [{0}] ", part));

Or

foreach (string Name in AllNames.Distinct().OrderBy(A => A))
{
    Debug.WriteLine(Name);
}

Oops, the above includes some of my abuses of LINQ. Doing a Distinct and then sorting the list, probably stretching the friendship with LINQ. But, what the heck it works 😉 !

Using the Foreach Extension Method

TokenList.ForEach(a => Debug.WriteLine(a));

the above is a quick dump of the contents of a List>String< to the debug console.

private List LookupType(DataElementsDataContext deDC, List InformationDataElements)
{
    List<string> result = new List>string<();
    InformationDataElements.ForEach(A => result.Add(LookupType(deDC, A)));
    return result;
}

An example of method invocation and adding to a list. I’ve also used LINQ to achieve the same sort of result:

var log1 = from line in ParsedLines
           select new LogMessage(line);

 

StringBuilder result = new StringBuilder();
bool First = true;
InformationNameDetails.ForEach(A =>
    {
    if(First)
        First = false;
    else
        result.Append(" and ");
    result.Append(A);
}
);

It is probably an abuse of the lambda expressions to include chunks of procedural logic. But, again it works for me, so what the heck!

Conclusions

There are more than one observatins which should be made at this point. The major ones are:

  • The use of the Foreach extension method certainly, seems to me, to be an effective way of “cleaning up” C# code, and removing some of the padding which is necessary for the foreach statement.
  • The Foreach extension method is something which could be over used. Well more to the point the complexity of the lambda expression could get greater than the language designers intended.
  • Moving to the method syntax for some foreach loops, opens the door to using the Parallel ForEach Method from the System.Threading.Tasks namespace. You’ve done most of the hard work in the writing of the lambda expression. What is left in the move to a parallel ForEach is a lot of work making sure that what you’re invoking can be done in a parallel manner safely.

References:

Advertisements

, , , , , , , , , , , ,

  1. Yield Return: Uses, Abuses and “Rules of Thumb” « Craig's Eclectic Blog
  2. LINQ on String using the IEnumerable<char> Interface « Craig's Eclectic Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: