Thursday, February 05, 2009

C# Map HOF goodness

The Map higher order function is provided in C# as the Select extension method.

So to cover the last step that I was going on about this morning, i.e. to transform this:

foreach(var field in (from field in TheForm.Fields where field.Disabled select field)) {
    field.DoSomething();
}

We can use method syntax (fluent) rather than query syntax to give the one liner:

TheForm.Fields.Where(field => field.Disabled).Select(field => field.DoSomething());

Neato!

Incidentally though, this seems to only work when DoSomething returns a non void. For example, if you try to compile:

TheForm.Fields.Where(field => field.Disabled).Select(field => Console.WriteLine(field.Name));

You will get an error:

The type arguments for method 'System.Linq.Enumerable.Select<TSource,TResult>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

This is pretty easy to fix though by changing the expression lambda to a statement lambda:

TheForm.Fields.Where(field => field.Disabled).Select(field => { Console.WriteLine(field.Name); return true; });

No comments:

Post a Comment