简体   繁体   English

C#-嵌套循环

[英]C# - Nested Loop

I'm doing a simple c# exercise. 我正在做一个简单的C#练习。 The problem is I want to show output such as: 问题是我想显示如下输出:

Output 输出量

Sample 1 => a 样本1 => a

Sample 2 => b 样本2 => b

Sample 1 => c 样本1 => c

Sample 2 => d 样本2 => d

Sample 1 => e 样本1 => e

Sample 2 => f 样本2 => f

Here's input 1 : 这是输入1:

Sample 1 => 
Sample 2 => 

Here's input 2 : 这是输入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.. 谢谢..

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.): 因此,您可以轻松地使用LINQ的Zip方法来实现此结果(也可以通过使用String.Join方法,我们没有使用任何循环。):

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

You can try using modulo (%), and use RichTextBox2.Lines as the outer loop. 您可以尝试使用模(%),并将RichTextBox2.Lines用作外部循环。

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. 看起来很复杂,但是即使有Sample 3,Sample 4等,模也可以为您提供所需的内容。

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++;
}

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. 其中input1[i]基本上转换为:例如,您必须将两个初始框的内容推入数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM