When I created the prototype of the MVC Toolkit (the HTML Helpers), there was a method in there that I was particularly fond of: ToFormattedList(). This Extension method would take an IEnumerable (or IEnumerable<T>) and create a simple formatted list out of it. It's since been replaced, but I liked it so much I thought I'd do a quick post about it.
This is a Public, Service, Announcement
There may be better ways to do this, but sometimes it's nice to just use one line of code to create an ordered list or unordered list. Rather than beat this to death, here's the code:
/// <summary> /// Creates a formatted list of items based on the passed in format /// </summary> public static string ToFormattedList(this IEnumerable list, ListType listType) { string outerListFormat = ""; string listFormat = ""; switch (listType) { case ListType.Ordered: outerListFormat = "<ol>{0}</ol>"; listFormat = "<li>{0}</li>"; break; case ListType.Unordered: outerListFormat = "<ul>{0}</ul>"; listFormat = "<li>{0}</li>"; break; case ListType.TableCell: outerListFormat = "{0}"; listFormat = "<td>{0}</td>"; break; default: break; } return string.Format(outerListFormat, ToFormattedList(list, listFormat)); }
/// <summary> /// Creates a formatted list of items based on the passed in format /// </summary> /// <param name="list">The item list</param> /// <param name="format">The single-place format string to use</param> public static string ToFormattedList(IEnumerable list, string format) { StringBuilder sb = new StringBuilder(); foreach (object item in list) { sb.AppendFormat(format, item.ToString()); } return sb.ToString(); }
I'm working with enums so I don't have to pass in strings (although I still can with the overload). My enum is declared like this:
/// <summary> /// Types of HTML Lists /// </summary> public enum ListType { Ordered, Unordered, TableCell }
You can have whatever lists you like here - options, table rows - whatever you need. I'm keeping this simple for the sake of the blog post here.
To use this, Extension method, you first need an Enumerable object. I'll use a string array, but any object will do. The ToString() method will be called on that object so you might want to override it's core methods if you're not using a primitive.
I've created a string array to test this method:
string[] names = new string[] { "larry", "moe", "curly" };
To output this as a list, all I need to do is reference the new "ToFormattedList()" method:
<%=names.ToFormattedList(ListType.Unordered)%>
This will output:
Hope you find this helpful.
