c# - 如何生成动态for循环

标签 c# loops dynamic for-loop

一个页面有5个级联组合框,是动态创建的。 当达到预期的总和时,我必须做点什么。这是我生成一些输出的代码;我想动态生成所有 for 循环甚至所有“cmb”数组。我怎样才能实现它?

private int[] cmb1 = { 0, 2, 4, 6, 8, 12, 16, 20 };
private int[] cmb2 = { 0, 2, 4, 6, 8, 12, 16, 20 };
private int[] cmb3 = { 0, 2, 4, 6, 8, 12, 16, 20 };
private int[] cmb4 = { 0, 2, 4, 6, 8, 12, 16, 20 };
private int[] cmb5 = { 0, 2, 4, 6, 8, 12, 16, 20 };
int count = 0;

        for (int i = 0; i < cmb1.Length; i++)
        {
            for (int j = 0; j < cmb2.Length; j++)
            {
                for (int k = 0; k < cmb3.Length; k++)
                {
                    for (int l = 0; l < cmb4.Length; l++)
                    {
                        for (int m = 0; m < cmb5.Length; m++)
                        {
                            if (cmb1[i] + cmb2[j] + cmb3[k] + cmb4[l] + cmb5[m] <= 20 && (i + j + k + l + m) != 0)
                            {
                                Console.WriteLine(count + " _ " + i + " " + j + " " + k + " " + l + " " + m);
                                count = count + 1;
                            }

                        }
                    }
                }
            }
        }

最佳答案

您要执行的操作可以被视为未知(在编译时)数量的序列的笛卡尔积。

Eric Lippert 写了一个 blog post关于如何在 C# 中创建这样的解决方案。他最终生成的代码是:

public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
    IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
    return sequences.Aggregate(
        emptyProduct,
        (accumulator, sequence) =>
        from accseq in accumulator
        from item in sequence
        select accseq.Concat(new[] { item }));
}

现在我们可以使用它:

List<int[]> cmbs = new List<int[]>();
cmbs.Add(new int[] { 0, 2, 4, 6, 8, 12, 16, 20 });
cmbs.Add(new int[] { 0, 2, 4, 6, 8, 12, 16, 20 });
cmbs.Add(new int[] { 0, 2, 4, 6, 8, 12, 16, 20 });

var query = cmbs.CartesianProduct()
    .Where(combo => combo.Sum() <= 20 && combo.Sum() > 0);

int count = 0;
foreach (var combo in query)
{
    Console.Write((count++) + " _ ");
    Console.WriteLine(string.Join(" ", combo));
}

关于c# - 如何生成动态for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18338689/

相关文章:

c++ - 如何知道MFC消息循环是否已经在运行?

java 替换数组的元素

c# - 这是使用 C# 动态的合理方式吗?

dynamic - retrofit 2 : How to handle dynamic response

java - JTree 单击事件不起作用

c# - ListView 中是否有针对空值的特殊模板或语法?

c# - ListBox.SelectedIndexChanged - 你能确定它是否是用户发起的吗?

c# - “任务”不包含 C# 的 'CompletedTask' 的定义

c# - 如何通过操作结果从另一个局部 View 更新局部 View

linux - BASH grep 脚本