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:
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