Search code examples
c#foreach

Foreach Write Headers and Footers Cleanly


I often have code that goes something like this.

StringBuilder sb = new StringBuilder();
IEnumerable<MyWidget> MyWidgets=GetMyWidgets();

if (MyWidgets.Count != 0)
{
    sb.Append("This is header text");

    foreach (MyWidget widget in MyWidgets)
    {
        sb.Append("This is info about widget: " + widget.SomeInfo);
    }

    sb.Append("This is footer text");
}

Is there some way to make this cleaner? Perhaps using lambda expressions or anonymous functions (I'm not familiar with those, so an example would be helpful)?

A real-world example is writing an HTML table if there are items present in the collection of objects.


Solution

  • StringBuilder sb = new StringBuilder();
    List<MyWidget> MyWidgets = GetMyWidgets().ToList();
    if(MyWidgets.Count!=0)
    {
        sb.Append("This is header text");
        MyWidgets.Foreach(w => sb.Append("This is info about widget: " + w.SomeInfo));
        sb.Append("This is footer text");
    }