You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中实现数组的n次笛卡尔幂遍历?

在C#中实现数组的n次笛卡尔幂(n层嵌套遍历效果)

嘿,我明白你想要实现的是类似Python itertools.product(array, repeat=n) 的功能——也就是生成数组的n次笛卡尔积,替代手动写n层嵌套foreach循环。在C#里我们可以通过几种方式实现,下面给你详细的方案:

方案1:手动实现递归版本

递归是处理这种动态层数嵌套问题的常用思路,核心是逐步构建每一层的组合:

using System;
using System.Collections.Generic;

public static class CartesianProductHelper
{
    public static IEnumerable<T[]> GenerateCartesianProduct<T>(T[] array, int repeat)
    {
        if (repeat <= 0)
        {
            yield return Array.Empty<T>();
            yield break;
        }
        
        foreach (var item in array)
        {
            foreach (var subProduct in GenerateCartesianProduct(array, repeat - 1))
            {
                var result = new T[repeat];
                result[0] = item;
                Array.Copy(subProduct, 0, result, 1, subProduct.Length);
                yield return result;
            }
        }
    }
}

使用示例:

int[] array = new int[] { 5, -4 };
int n = 3;

foreach (var newArray in CartesianProductHelper.GenerateCartesianProduct(array, n))
{
    Console.WriteLine($"[{string.Join(", ", newArray)}]");
}

这段代码会输出所有3次笛卡尔积的组合:[5, 5, 5]、[5, 5, -4]、[5, -4, 5]、[5, -4, -4]、[-4, 5, 5]等等。

方案2:用LINQ的Aggregate方法实现

如果你更偏好LINQ风格的代码,可以用Aggregate来累积生成笛卡尔积,代码更简洁:

using System;
using System.Collections.Generic;
using System.Linq;

public static class CartesianProductHelper
{
    public static IEnumerable<IEnumerable<T>> GenerateCartesianProduct<T>(T[] array, int repeat)
    {
        IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() };
        
        for (int i = 0; i < repeat; i++)
        {
            result = from seq in result
                     from item in array
                     select seq.Concat(new[] { item });
        }
        
        return result;
    }
}

使用示例:

int[] array = new int[] { 5, -4 };
int n = 2;

foreach (var combination in CartesianProductHelper.GenerateCartesianProduct(array, n))
{
    Console.WriteLine($"[{string.Join(", ", combination)}]");
}

这个版本返回的是IEnumerable<IEnumerable<T>>,如果需要转换成数组,可以在遍历的时候调用ToArray()。

方案3:使用第三方库(可选)

如果你不想自己写实现,可以使用第三方库MoreLINQ,它里面内置了Product方法,支持指定repeat参数:

首先通过NuGet安装MoreLINQ包,然后使用:

using MoreLinq;

int[] array = new int[] { 5, -4 };
int n = 3;

foreach (var newArray in array.Product(n))
{
    Console.WriteLine($"[{string.Join(", ", newArray)}]");
}

这个方法和Python的itertools.product用法几乎一致,非常方便。


内容的提问来源于stack exchange,提问作者Theo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:32:25