c#使用LINQ限制递归列表

本文关键字:递归 列表 使用 LINQ | 更新日期: 2023-09-27 18:04:03

我想弄清楚如何使用LINQ来限制递归调用。

我使用以下代码的目的是遍历一个数字列表(num),并对每个数字递归计数/打印到设置的数量(6)。

我想要得到的newnum序列是:3 45123.45523.45

但是我自然会进入一个无限循环。.Where谓词并没有像我想象的那样停止循环,很可能是我的基本情况关闭了。有什么好办法吗?谢谢你。

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);   // is this possible?
    newnum.ToList().ForEach( w => Console.WriteLine(w));

我注意到下面的示例代码中出现了类似的停止模式,.Where将只包括小于7的阶乘,我错过了什么?

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);

c#使用LINQ限制递归列表

答案是您没有基本情况。一旦你的递归函数被执行,没有什么可以阻止它——LINQ不会执行任何可以修改另一个函数的内部逻辑的魔法。

在这个例子中,你缺少了停止递归的关键代码位——基本情况:

locFactorial = n => n == 1 ? 1 : n * locFactorial(n - 1);

三元运算符检查n==1是否存在,如果是,则返回1。这是您的函数所缺少的基本情况。

没有办法单独通过LINQ为函数提供基本情况。您需要将其构建到递归函数中。

另外,如果您想从单个数字返回数字列表,则从递归函数返回错误的类型:这与Factorial函数从根本上不同,后者返回单个数字给定单个数字。

下面是一个不使用递归的函数:

void Main()
{
    var numbers = new[] {3, 1, 8, 5, 2};
    numbers.SelectMany(x => GetIncreasing(x).TakeWhile(y => y < 6));
}
IEnumerable<int> GetIncreasing(int x)
{
   while (true)
       yield return x++;
}

您可以坚持生成符合您需求的序列,例如:

var num = new[] { 3, 1, 8, 5, 2 };
var limit = 6;
var query = from n in num
            where n < limit // sanity check
            from pn in Enumerable.Range(n, limit - n)
            select pn;

良好的性能和干净的代码

与阶乘样本的不同之处在于结束条件的位置。你应该这样做:

recursiveWrite = n => 
                    {
                        Console.WriteLine("string " + n);
                        if (n < 6)
                            recursiveWrite(n+1);
                        return n;
                    };

不完全确定您想要实现的目标,但我希望这将有所帮助。在递归lambda中需要一个停止条件(如n==1在阶乘中)。通过嵌套函数,你可以"动态地"注入这个限制。

class Program
{
    static void Main(string[] args)
    {
        var num = new[] { 3, 1, 8, 5, 2 };
        Func<int, Func<int, IEnumerable<int>>> writeString = 
            delegate(int maxcount)
            {
                Func<int, IEnumerable<int>> recursiveWrite = null;
                recursiveWrite = (n) =>
                    {
                        if (n < maxcount)
                        {
                            Console.WriteLine("string " + n);
                            var rec = recursiveWrite(n + 1);
                            return new List<int>(){n}.Concat(rec);
                        }
                        return new List<int>();
                    };
                return recursiveWrite;
            };
        var newnum = num.SelectMany(n => writeString(6)(n));   // is this possible?
        newnum.ToList().ForEach(w => Console.WriteLine(w));
        Console.ReadLine();
    }
}