一个页面有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/