Lambda Loop

August 31, 2011

Very quick tip…instead of a ‘traditional’ For Each loop:

foreach (String s in stringList)
    LabelOutput.Text += s + "<br/>";

Consider a Lambda loop:

stringList.ForEach(s => LabelOutput.Text += s + "<br/>")

The result is less code, more readable code (IMHO!) and having tested both with 10,000 strings in a list, it seems there is no impact on performance.

You can of course filter the list using a Lambda expression, still on the 1 line of code:

stringList.Where(s => s.Contains(foo)).ForEach(s => LabelOutput.Text += s + "<br/>")

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: