Here is an example of how to write a recursive traversal using a recursive lambda expression and using the SelectMany method from LINQ:
Func<string, IEnumerable<string>> folders = null; folders = s => Directory.GetDirectories(s).SelectMany(dir => Enumerable.Concat(new[] { dir }, folders(dir))); foreach (var d in folders("C:\\Tomas\\Writing\\Academic")) Console.WriteLine(d);
The first line declares the lambda expression in advance, because we use it later in its definition. This is not a problem because it will be used after its initialization, but the C # compiler requires us to declare this earlier.
The body of the lambda expression calls SelectMany , which calls the given lambda expression for each element of the input sequence and combines all the returned sequences - our lambda returns the current dir directory and then all the recursively computed dir subdirectories.
This is probably not particularly effective, but it definitely shows how you can use lambda functions to write short code (it could be optimized, however, the F # libraries do this because it is a more common template in F #).
Just for comparison, the same thing in F # looks like this:
let folders s = seq { for dir in Directory.GetDirectories(s) yield dir yield! folders dir }
The code uses sequence expressions similar to C # iterators. yield corresponds to yield return , and yield! gives all the elements of a sequence (it's like iterating over it using foreach and providing individual elements using yield return , but more efficient).
source share