Implementing the Each method in C# collections.

Published on Dec 31, 2007

The Javascript library Prototype make use of “prototypes” to extend some internal JavaScript objects like the Array. One of the extension methods that I find myself using the most is the each method.

Examples

We also have the each method in Ruby.

Using Alex suggestions I’m changing the delegates by Action<T> and Func<T,T> and using yield allow me to extend IEnumerable now. The code is way more elegant this way, thanks Alex.

This example will output the ToString() method of each object into the string. You can also modify the content of the Collection using the overload method and the delegate that returns an object.

This is the output:

Pretty cool, isn’t it? The power of using a delegate should not be overlooked since you could tie the delegate to multiple methods to further process each element of the collection.