WrapEachWithTag

public static string WrapEachWithTag<T>(this IEnumerable<T> source, string tagToWrap)
{
    var tag = String.Format("</{0}>", tagToWrap);
    var s = "";
    foreach (T item in source)
    {
        s += tag.Replace(@"/", "") + item.ToString() + tag;
    }
    return s;
}
Example:
IEnumerable<string> employeeNames = GetEmployeeNames();
myDiv.InnerHtml += "<ul>";
myDiv.InnerHtml += employeeNames.WrapEachWithTag("li");
myDiv.InnerHtml += "</ul>";

// prints: "<ul><li>Bob</li><li>Fred</li><li>Anne</li></ul>"

Description

Creates a string that is each the elements' ToString() values wrapped in the 'tag' that is passed as a param. Good for converting an IEnum<T> into a block of HTML/XML.

Details

Double click on the code to select all.

 

;