C#: Comparing ways to iterate lists in C# and some lambda expression examples

As one who has been learning  .NET and C# since it was first public preview I’ve found it interesting to follow how the language has developed.

One way to see how expressive C# has become is to compare ways how to iterate collections. I also hope this helps you to understand lambdas (new in C# 3.0) better.

C# 1.0 – foreach

This first example shows how I usually iterated a collection of objects in C# 1.0:

//C# 1.0 Basic Approach

foreach (Product product in products)

{

    WriteOutProduct(product);

}

This is very familiar way for almost any coder of any syntax and it is probably self-explanatory for non-coders, too.

The products -object is of generic type List<Product>. Generics didn’t exists in C# 1.0 (how did we ever manage?), but that basic foreach-method works with any array or IEnuramble -collection.

C# 2.0 – Anonymous Methods

Anonymous Methods were introduced when C# 2.0 was released.

After that we could alternatively go through the items like this:

//C# 2.0 Anonymous Method Approach

products.ForEach(delegate(Product product)

{

    WriteOutProduct(product);

});

While the performance is good for this method, the syntax is quite hard to remember and hard to read. Note that the ForEach is a method in List<T> and it doesn’t automatically exist in all collection types.

When the method has only one parameter that takes an object as a parameter like in the example above, the call can actually be shortened into form:

products.ForEach(WriteOutProduct);

While this is probably the neatest way, it won’t work when the method requires more than one parameter (as far as I know). Then it has to be expanded to a form described in the previous example.

C# 3.0 – Lambda Expressions

I’m fan of simple and fast syntaxes and the more I get used to Lambda-expressions, the more I like them.

Here is an example, how to achieve the same result using the lambda-expression:

//C# 3.0 Lambda Expression Approach

products.ForEach(product => WriteOutProduct(product));

It takes a few tries to get used to the lambda expression as the order of parameters may be little confusing at first. But once you do, it’ll come out naturally.

More lambda examples

Here are some more examples to get your ideas flowing. For some  cases LINQ to SQL could be better candidate as it limits the results of the query already in the database-side. However, sometimes you want to get subset from collections without extra round-trip to the database and that’s when these methods are useful.

LINQ is also a very good alternative for doing queries to the objects, but in simple cases I prefer this even shorter syntax. When queries and objects are more complex, then LINQ has more power, but that’s outside the scope of this post.

For these examples I have used a typical method that returns a list of all products:

private static List<Product> GetProducts() { …

With lambdas I could filter the results to those products that cost more than 50:

List<Product> products = GetProducts().FindAll(product => product.UnitPrice > 50);

Or get only those products whose names start with "A":

List<Product> products = GetProducts().FindAll(product => product.ProductName.StartsWith("A"));

Or sum the prices:

double sum = GetProducts().Sum(product => product.UnitPrice);

Have fun :)

3 Responses to “C#: Comparing ways to iterate lists in C# and some lambda expression examples”

  1. C#’s Lamba ForEach: Only on Lists? at Mark Needham Says:

    [...] of my favourite things introduced into C# recently is the new ForEach method which can be applied to (apparently only!) [...]

  2. John Says:

    Awesome post, with nice, simple examples… I may start using lambda expressions after all! thanks

  3. jemm Says:

    @John: Thanks for the comment :) Lambdas are really nice for writing tidy code. There are several other good examples around the net. http://www.dotnetkics.com is a good place to start looking for more samples :)

Leave a Reply