#region 测试用初始化数据
int x = 3;//x值是不定的
object[][] list = new object[x][];//交错数组类型是一个实体类,这里用object代替
for (int i = 0; i < list.Length; i++)
{
int len = new Random().Next(2, 8);//测试数据数组的长度不定取一个随机数
list[i] = new string[len];
string str = null;//输出测试结果用
for (int j = 0; j < len; j++)
{
list[i][j] = ((char)(i + 97)).ToString() + j;//这里i+97(即字母a)目的是让测试数组更直观
str += (list[i][j].ToString() + ',');
}
Console.WriteLine("list[" + i + "]:" + str.TrimEnd(','));
}
#endregion这里假设初始数据为(即输出结果):
list[0]:a0,a1,a2
list[1]:b0,b1
list[2]:c0,c1
//我需要组合成下面这样一个数组,这个算法该如何写?简单的for嵌套肯定是不行的,因为数组长度不定,想想应该要用到递归,但没想明白应该如何写!
result[0]: a0,b0,c0
result[1]: a0,b0,c1
result[2]: a0,b1,c0
result[3]: a0,b1,c1
result[4]: a1,b0,c0
result[5]: a1,b0,c1
result[6]: a1,b1,c0
result[7]: a1,b1,c1
result[8]: a2,b0,c0
result[9]: a2,b0,c1
result[10]: a2,b1,c0
result[11]: a2,b1,c1
void Main()
{
var list=new List<List<string>>
{
new List<string>{"a0","a1","a2"},
new List<string>{"b0","b1"},
new List<string>{"c0","c1"}
};
var result=from a in list.First()
from b in list.Skip(1).Take(1)
from c in b
from d in list.Last()
select new{a,c,d};
result.ToList().ForEach(r=>Console.WriteLine("{0}\t{1}\t{2}",r.a,r.c,r.d));
/*
a0 b0 c0
a0 b0 c1
a0 b1 c0
a0 b1 c1
a1 b0 c0
a1 b0 c1
a1 b1 c0
a1 b1 c1
a2 b0 c0
a2 b0 c1
a2 b1 c0
a2 b1 c1
*/
}
q107770540大哥的方法是够简洁呀,不过由于数组的长度不定(即list的长度不确定的)这种方式可能不行
public static void Test()
{
var list = new List<List<string>>
{//list里可以任意类型的对象
new List<string>{"a0","a1","a2"},
new List<string>{"b0","b1"},
new List<string>{"c0","c1","c2"}
};
var result = Descartes(list);
int k = 0;
foreach (var s in result)
{
string str = null;
foreach (var item in s)
{
str += item + ",";
}
Console.WriteLine(k++ + "\t" + str.TrimEnd(','));
}
} private static List<List<T>> Descartes<T>(List<List<T>> list)
{
List<List<T>> result = new List<List<T>>();
foreach (List<T> values in list)
{
if (result.Count == 0)
{
foreach (var value in values)
{
result.Add(new List<T> { value });
}
}
else
{
result = JoinPart(result, values);
}
}
return result;
} public static List<List<T>> JoinPart<T>(List<List<T>> part1, List<T> part2)
{
var result = new List<List<T>>();
foreach (var item1 in part1)
{
foreach (var item2 in part2)
{
List<T> item = new List<T>(item1);//此处相当于复制item1(引用类型必须复制item1)
item.Add(item2);
result.Add(item);
//result.Add(item1 + " " + item2);
}
}
return result;
}
#endregion