0

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..

2
  • I don't think you need a nested-loops, maybe a int to flip remember the position of input1 is fine Commented Sep 19, 2016 at 4:47
  • 1
    "it doe's not work" is a uselessly unspecific problem description, especially given the lack of a good minimal reproducible example that reliably reproduces whatever problem you have. Commented Sep 19, 2016 at 4:47

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

You need to corresponding elements of two sequences. So you can use LINQ's Zip method easily to achieve this result like this (Also by using String.Join method we didn't use any loop.):

richTextBox3.Text = String.Join(Environment.NewLine, 
                    Enumerable.Repeat(richTextBox1.Lines, richTextBox2.Lines.Count())
                    .SelectMany(c => c).Zip(richTextBox2.Lines, (f, s) => f + " => " + s));

Comments

1

Here is the code that would give you the expected output:

int i = 0;
foreach (var input2 in RichTextBox2.Lines)
{
    string input1 = RichTextBox1.Lines[i % RichTextBox1.Lines.Length];
    RichTextBox3.Text += input1 + input2 + Environment.NewLine;
    i++;
}

Comments

0

Your problem is that your are looping your second input ... for each first input! Again, and again, and again.

So: you only need one loop here. Here is some pseudo code to get started:

... first check that both line counts are equal
for (int i=0; i<linecount; i++) {
    RichTextBox3.Text += input1[i] + input2[i] + Environment.NewLine
}

Where input1[i] basically translates to: you have to push the content of your two initial boxes into an array for example.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.