提问者:小点点

使C#foreach打印一次


我被这个聪明的问题困住了。我找不到一个可定制的解决方案。我正在尝试使用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

并对列表的其余部分依此类推。谁能指导我解决这件事。任何帮助都非常感谢。


共1个答案

匿名用户

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());