Home > database >  How to do a foreach loop with multiple lists
How to do a foreach loop with multiple lists

Time:06-20

I am trying to do a foreach loop that runs through 3 lists. Here is what I have currently:

foreach (Button btn in appList && sequenceLsit && FunctionList)
{
    if (btn.FillColor != Color.White) 
    {
        // Do stuff
    }
}

I tried using tuples, but as I understand, they use a separate variable for each list. I need a single variable (btn) for all 3 lists.

CodePudding user response:

A foreach loop enumerates one list. If you have three separate lists then you need to create one list from them first, which can then be enumerated. The simplest way to do that is the Enumerable.Concat extension method:

foreach (Button btn in appList.Concat(sequenceLsit).Concat(FunctionList))

CodePudding user response:

There's a few ways to solve this. You can:

  1. Iterate through each list one at a time (foreach inside foreach inside foreach) as mentioned by John
  2. Union your lists together if they share the same type (how are your lists declared?) and then iterate through them once with a single foreach loop

Also, you can use LINQ to remove the need for the IF statement, like this: foreach (var btn in appList.Where(x => x.FillColor != Color.White)) {...}

CodePudding user response:

You can use Enumerable.Concat method

foreach (Button btn in appList.Concat(sequenceLsit).Concat(FunctionList))
{
    if (btn.FillColor != Color.White) 
    {
        // Do stuff
    }
}

CodePudding user response:

@John provided you with .Concat, but you may be able to solve your problem with a different approach:

  1. Create method that works on a button
    var CheckButtons(IEnumerable<Button> buttons) 
    {
      foreach (Button btn in buttons)
      {
         if (btn.FillColor != Color.White) 
         {
            // Do stuff
         }
      }
    }
    ...
    
  2. Call it on your lists:
    CheckButtons(appList);
    CheckButtons(sequenceLsit);
    CheckButtons(FunctionList);
    
  • Related