2010-05-27 67 views
0

我有一个List,我将它分组到不同的列表中。来自c中不同列表的所有组合的连接#

来源:

List -> "a","b","c","it","as","am","cat","can","bat" 

进入

List1 -> -a,b,c 
List2 -> it,as,am 
List3 -> cat,can,bat 

我如何Concat的所有可能的组合从这个名单,与像输出:通过每个列表中

 
a,it,cat 
b,it,cat 
c,it,cat 
a,am,cat 
b,am,cat 
c,am,cat 
. 
. 
. 
. 
etc so on... 

回答

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

如何

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; 
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可言。无论你需要怎样处理结果...