Search code examples
c#loopsfor-loopforeachnested-loops

C# - Nested Loop


I'm doing a simple c# exercise. The problem is I want to show output such as:

Output

Sample 1 => a

Sample 2 => b

Sample 1 => c

Sample 2 => d

Sample 1 => e

Sample 2 => f

Here's input 1 :

Sample 1 => 
Sample 2 => 

Here's input 2 :

a
b
c
d
e
f

Here's my code

foreach (string input1 in RichTextBox1.Lines)
{
    foreach (string input2 in RichTextBox2.Lines)
    {
        RichTextBox3.Text += input1 + input2 + Environment.NewLine;
    }
}

But it doe's not work .can anyone help me. thank you..


Solution

  • You can try using modulo (%), and use RichTextBox2.Lines as the outer loop.

    for (int i=0; i<RichTextBox2.Lines.Length; i++)
    {
        var length = RichTextBox1.Lines.Length;
        RichTextBox3.Text += RichTextBox1.Lines[(i%length)] + RichTextBox2.Lines[i] + Environment.NewLine;
    }
    

    Looks complicated, but modulo gives you what you want even if there is a Sample 3, Sample 4, and so on.