views:

58

answers:

3

I have a List and I'm grouping it into different lists.

From:

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

Into

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

How can I concat the all possible combination from this lists, with output like:

a,it,cat
b,it,cat
c,it,cat
a,am,cat
b,am,cat
c,am,cat
.
.
.
.
etc so on...
+2  A: 

Just loop through each list in a nested fashion and combine:

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();
Oded
+1  A: 

How about

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;
B4ndt
+1  A: 
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));
}

Of course you can turn it directly into a list using ToList(), then you don't need the foreach at all. Whatever you need to do with the result ...

Stefan Steinegger