是否可以在C#中的一行中生成两行输出文本? [英] Is it possible to make two lines of output text in one line in C#?
本文介绍了是否可以在C#中的一行中生成两行输出文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果有两行输出文本在不同的for循环中,有什么方法可以将它们放在同一行中?以下是我要编辑的代码:
Is there any way I can make the two lines of output text in the same line if they are in different for-loops? The following is the code that I want to edit:
foreach (object s in roomType)
{
++roomCounter;
Console.WriteLi("Room {0} Name: {1} State : {2} ", roomCounter, s); // first line want to concatenate
}
foreach (object t in FurnishedFinished)
{
++roomCounter;
Console.Write(" State : {0} ",t); // second line }
我希望输出为 -
I want the output to be -
"Room {0} Name: {1} State : {2} State :{3}"
但是我无法进行嵌套的for循环,因为如果我使用嵌套方法,还会出现其他问题。
我尝试过:
but I cannot make a nested for-loop because there are other issues that keep coming up if i use the nested method.
What I have tried:
foreach (object s in roomType)
{
++roomCounter;
Console.Write("Room {0} Name: {1} State : {2} ", roomCounter, s); // first line want to concatenate
}
foreach (object t in FurnishedFinished)
{
++roomCounter;
Console.Write(" State : {0} ",t); // second line }
推荐答案
你给出的例子不起作用 - 你只提供两个参数,但在格式字符串。
你不能直接做你想做的事 - 一旦你输出到控制台,那就是它,你不能回去并轻松添加到线条。
试试这个:
The example you give won't work - you are only providing two arguments, but specifying three in the format string.
You can't do what you want to directly - once you output to the console, that's it, you can't go back and add to the lines that easily.
Try this:
List<StringBuilder> lines = new List<StringBuilder>();
foreach (object s in roomType)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Room {0} Name: {1} State : {2} ", roomCounter++, s, "hello third Parameter");
lines.Add(sb);
}
int i = 0;
foreach (object t in FurnishedFinished)
{
lines[i++].AppendFormat(" State : {0} ", t);
}
foreach (StringBuilder sb in lines)
{
Console.WriteLine(sb.ToString());
}
看一下 StringBuilder
:在.NET Framework中使用StringBuilder类 [ ^ ]
最简单的解决方案是不使用foreach循环并将其替换为简单的for循环:
Easiest solution is not using a foreach loop and replacing it with a simple for loop:
for (int i=0; i< roomtype.length; i++)
{
++roomCounter;
Console.Write("Room {0} Name: {1} State : {2} ", roomCounter, roomType[i]); // first line want to concatenate
Console.Writeli(" State : {0} ", FurnishedFinished[i]); // second line
}
这篇关于是否可以在C#中的一行中生成两行输出文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文