user2606722
user2606722

Reputation:

Dynamically append foreach statements to c# code

I'm busy on a c# project where I have a List{1,2,3}. I want to form all possible matches between the elements of the List object. That would be easy to do by using 3 foreach loops.

foreach(int one in list)
{
     foreach(int two in list)
     {
           foreach(int three in list)
           {
                  // ...
            }}}

But if I don't know the amount of elements in the list object : how can I do all matches by using foreach loops?So if there are 6 elements in the list, then there should be 6 underlying foreach loops... (I don't want to use if statements as seen as it uses too much space) And if I use foreach loops, how can I dynamically change the name of the variable used in the foreach loop? (Can you say :

     String "number"+i = new String("..."); //where i = number (int)

EDIT :

The output should be :

 1,1,1
 1,2,1
 1,2,2
 1,2,3
 1,3,1
 1,3,2
 1,3,3
 ...

Upvotes: 2

Views: 259

Answers (2)

lordkain
lordkain

Reputation: 3109

another approach is to get the current item and the rest. Then you can do your thing also

foreach (var one in ItemList)
{
  var currentItem = one;
  var otherItems = ItemList.Except(currentItem);

  // Now you can do all sort off things
}

Upvotes: 0

Ehsan
Ehsan

Reputation: 32681

From your definition i guess you need a power set. Example taken from here

public static IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list)
{
        return from m in Enumerable.Range(0, 1 << list.Count)
               select
                   from i in Enumerable.Range(0, list.Count)
                   where (m & (1 << i)) != 0
                   select list[i];
}

private void button1_Click_2(object sender, EventArgs e)
{
        List<int> temp = new List<int>() { 1,2,3};

        List<IEnumerable<int>> ab = GetPowerSet(temp).ToList();
        Console.Write(string.Join(Environment.NewLine,
                                 ab.Select(subset =>
                                 string.Join(",", subset.Select(clr => clr.ToString()).ToArray())).ToArray()));
}

OUTPUT:

1
2
1,2
3
1,3
2,3
1,2,3

Upvotes: 1

Related Questions