我被这个聪明的问题困住了。我找不到一个可定制的解决方案。我正在尝试使用foreach
打印列表的列表
。这是代码:
int i = 0;
StringBuilder sb = new StringBuilder();
foreach (var subList in result)
{
i++;
Console.WriteLine(sb.Append("******\n").Append("Group ").Append(i).Append(" - ").
Append("Number of students: ").Append(subList.Count()).Append("\n").Append("
Name:").Append("\n"));
var exp = subList.GetEnumerator();
while (exp.MoveNext())
{
Console.WriteLine(sb.Append(" ").Append(exp.Current.ToString()).Append("\n"));
}
}
我试图得到这个结果(例如):
Group 1 - Number of students: 3
Name:
this
is
a
Group 2 - Number of students: 3
Name:
test
again
and-again
等等。问题是,我总是得到这样的信息(每次都是从foreach
打印出来的):
Console.WriteLine(sb.Append("******\n").Append("Group ").Append(i).Append(" - ").
Append("Number of students: ").Append(subList.Count()).Append("\n").Append("
Name:").Append("\n"));
像这样:
******
Group 1 - Number of students: 3
Name:
******
Group 1 - Number of students: 3
Name:
this
******
Group 1 - Number of students: 3
Name:
this
is
******
Group 1 - Number of students: 3
Name:
this
is
a
并对列表的其余部分依此类推。谁能指导我解决这件事。任何帮助都非常感谢。
对sb.append
的每次调用不需要console.writeline
。您需要完全构建字符串,然后一次打印所有字符串
int i = 0;
StringBuilder sb = new StringBuilder();
foreach (var subList in result)
{
i++;
sb.Append("******\n")
.Append("Group ")
.Append(i)
.Append(" - ")
.Append("Number of students: ")
.Append(subList.Count())
.Append("\n")
.Append("Name:")
.Append("\n");
foreach(var exp in subList)
{
sb.Append(" ").Append(exp.ToString()).Append("\n");
}
}
Console.Write(sb.ToString());