HTML ListFormatter
My version of the ListFormatter(s) posted here. Based off the code posted by Joe Chung in the comments. The only real modification was I added overloads for params Func<T, object> and in inline format string. This allows strongly typed code like this:
<%=Model.Contacts.ToFormattedList(ListType.Unordered, "{0} - {1}", x => x.FirstName,x => x.LastName)%>
Useful? Maybe, maybe not.
public enum ListType
{
Ordered,
Unordered,
TableCell,
TableRow
}
public static class ListFormatter
{
public class ListFormats
{
public string ItemFormat { get; set; }
public string ListFormat { get; set; }
}
private static readonly IDictionary<ListType, ListFormats> Formatters = new Dictionary<ListType, ListFormats>();
static ListFormatter()
{
Formatters.Add(ListType.Ordered, new ListFormats { ItemFormat = "<li>{0}</li>", ListFormat = "<ol>{0}</ol>" });
Formatters.Add(ListType.Unordered, new ListFormats { ItemFormat = "<li>{0}</li>", ListFormat = "<ul>{0}</ul>" });
Formatters.Add(ListType.TableCell, new ListFormats { ItemFormat = "<td>{0}</td>", ListFormat = "{0}" });
Formatters.Add(ListType.TableRow, new ListFormats { ItemFormat = "<tr>{0}</tr>", ListFormat = "<table>{0}<table>" });
}
public static string ToFormattedList<T>(this IEnumerable<T> items, ListType type)
{
return FormattedList(items, type);
}
public static string ToFormattedList<T>(this IEnumerable<T> items, ListType type, Func<T, object> toString)
{
return FormattedList(items, type, toString);
}
public static string ToFormattedList<T>(this IEnumerable<T> items, ListType type, string format, params Func<T, object>[] toString)
{
return FormattedList(items, type, format, toString);
}
public static string FormattedList<T>(IEnumerable<T> items, ListType type)
{
return FormattedList(items, type, s => s.ToString());
}
public static string FormattedList<T>(IEnumerable<T> items, ListType type, Func<T, object> toString)
{
var listFormat = Formatters[type].ListFormat;
var itemFormat = Formatters[type].ItemFormat;
var itemsProjected = items.Select(item => string.Format(itemFormat, toString(item)));
return string.Format(listFormat, string.Join(string.Empty, itemsProjected.ToArray()));
}
public static string FormattedList<T>(IEnumerable<T> items, ListType type, string format, params Func<T, object>[] toStrings)
{
var listFormat = Formatters[type].ListFormat;
var itemFormat = Formatters[type].ItemFormat;
var sb = new StringBuilder();
foreach (var item in items)
sb.AppendFormat(itemFormat, InvokeOnItem(item, format, toStrings));
return string.Format(listFormat, sb);
}
public static string InvokeOnItem<T>(T item, string format, Func<T, object>[] toStrings)
{
var projected = new object[toStrings.Length];
for (var i = 0; i < projected.Length; i++)
projected[i] = toStrings[i].Invoke(item);
return string.Format(format, projected);
}
}