I am trying to figure out how to use LINQ to restrict a recursive call.
My intention with the following code is to execute a list of numbers ( num ) and for each number read / print recursively to a given number ( 6 ).
The sequence in newnum that I am trying to get is: 3 4 5 1 2 3 4 5 5 2 3 4 5
but naturally I came across an infinite loop. The .Where predicate .Where not stop the loop as I thought, and probably my base case is off. Any insight on how to properly install this? Thanks.
var num = new[] {3, 1, 8, 5, 2}; Func<int, int> writeString = delegate(int count) { Func<int, int> recursiveWrite = null; recursiveWrite = n => { Console.WriteLine("string " + n); recursiveWrite(n+1); return n; }; return recursiveWrite(count); }; var newnum = num.Where(n => writeString(n) < 6);
I noticed that a similar stop pattern is found in the following code example .Where will only include factorials less than 7, what am I missing?
var numbers = new[] { 5,1,3,7,2,6,4}; Func<int, int> factorial = delegate(int num) { Func<int, int> locFactorial = null; locFactorial = n => n == 1 ? 1 : n * locFactorial(n - 1); return locFactorial(num); }; var smallnums = numbers.Where(n => factorial(n) < 7);
source share