我有一个List,我将它分组到不同的列表中。
自:
List -> "a","b","c","it","as","am","cat","can","bat"
向
List1 -> -a,b,c
List2 -> it,as,am
List3 -> cat,can,bat
如何从此列表中连接所有可能的组合,输出如下:
a,it,cat b,it,cat c,it,cat a,am,cat b,am,cat c,am,cat . . . . etc so on...
答案 0 :(得分:2)
以嵌套方式循环遍历每个列表并组合:
StringBuilder sb = new StringBuilder();
for(int i =0; i < list1.Length; i++){
for(int j =0; j < list2.Length; j++){
for(int x =0; x < list3.Length; x++){
sb.AppendFormat("{0},{1},{2}\n", list1[i], list2[j], list3[x]);
}
}
}
string result = sb.ToString();
答案 1 :(得分:1)
怎么样
List<string> l1 = new List<string>();
List<string> l2 = new List<string>();
List<string> l3 = new List<string>();
l1.Add("1");
l1.Add("2");
l1.Add("3");
l2.Add("a");
l2.Add("b");
l2.Add("c");
l3.Add(".");
l3.Add("!");
l3.Add("@");
var product = from a in l1
from b in l2
from c in l3
select a+","+b+","+c;
答案 2 :(得分:1)
List<string> result = new List<string>();
foreach (var item in list1
.SelectMany(x1 => list2
.SelectMany(x2 => list3
.Select(x3 => new { X1 = x1, X2 = x2, X3 = x3 }))))
{
result.Add(string.Format("{0}, {1}, {2}", item.X1, item.X2, item.X3));
}
当然,您可以使用ToList()
将其直接转换为列表,然后根本不需要foreach
。无论你需要做什么结果......