← Back to all articles

Function as Enumerable

I've found that converting a function into an enumerable (or an observable) can be a neat trick at times. Consider the following.

public static IEnumerable<T> ToEnumerable<T>(this Func<T> f)
{
    yield return f();
    yield break;
}

Here is a small example concatenating two functions.

Func<string> a = () => "hello";
Func<string> b = () => "world";

var query = a.ToEnumerable().Concat(b.ToEnumerable());

foreach (var i in query)
    Console.WriteLine(i);

OUTPUT

hello
world

Or we could do something a little more interesting like leverage merge to schedule each function call on its own thread & then memoize the results in the order that they came in.

Func<string> a = () => { Thread.Sleep(5000); return "a"; };
Func<string> b = () => { Thread.Sleep(1000); return "b"; };
Func<string> c = () => { Thread.Sleep(2000); return "c"; };

var race = EnumerableEx
                .Merge(a.ToEnumerable(), b.ToEnumerable(), c.ToEnumerable())
                .MemoizeAll();

race.Run(Console.WriteLine);
Console.WriteLine(DateTime.Now);
// 2nd time will run instantly - it's memoized!
race.Run(Console.WriteLine);
Console.WriteLine(DateTime.Now);

OUTPUT

b
c
a
27/04/2010 23:59:19
b
c
a
27/04/2010 23:59:19

Comments