NET 4.0: New and useful LINQ extensions to the IEnumerable

Few months ago I made post with comparison of Ruby, Java and C# code to read all lines from text file. That time I have to code ForEach extension method for IEnumerable<T>. It allows executing arbitrary code against each element of the sequence. I believe most people already have this method.

Other languages already have such construct. For example iter in functional languages like F# or ForEach for List<T> in C# or each in ruby. IMHO this construct is really usable.

Anyways, today is good day. Doing fast review of the Reactive Extensions API (abbreviated form is Rx) I found library System.Interactive.dll. The only public class is EnumerableEx. And yes, it holds bunch of extension methods for the IEnumerable.

First extensions that got my attention is Do and Run. Both invoke Action<T> for every single element. Do is lazy, while Run is not. Code form previous post could be rewritten:


Another one is MemoizeAll. This is funny because today, Oren Eini (Ayende Rahien) found performance problem with UberProf. His solution to the problem is ToList(). ToList() converts lazy IEnumerable<T> to List<T> effectively break laziness. MemoizeAll is another and probably better solution for the problem. It caches results of previous execution but works in lazy way. So his code will look like this:

var statements = session.Statements.Where(x => filter(x)).MemoizeAll();
return new SessionStatistics
    NumberOfStatments = statements.Count(....);
    NumberOfCashedStatments = statements.Count(....);

This will execute Where statment exactly once. In contrast to original code it will do this in lazy way (in this case in constructor of the SessionStatistics).

Moving forward. If you need to defer creation of the enumerable, use Defer. If you need execute some stuff at the end of the sequence, use Finally. If you need repeat your sequence, use the obvious Repeat. What about prepending elements to the sequence? Use StartsWith. And this is not the complete list. It has about two dozens of extensions. You can visit unofficial wiki with list of this methods.

Go ahead, download Reactive Extensions API and explore this stuff yourself, it really usable! It available for both .NET 3.5 SP1 and .NET 4.0.

BTW, I do not know why this stuff is part of the Rx, it should be Core.

Have a good day!