How many times have you had to parse through a collection of objects, outputting nothing more than a comma-delimited list of items in the result set. Typically, you’ll do this:
<asp :repeater runat="server"> <itemtemplate>Eval("Name")</itemtemplate> <separatortemplate>, </separatortemplate> </asp>
If you were parsing a list of states, it might look like this:
Alabama, Alaska, Arizona, Arkansas
There’s an easier way to handle these simple needs: create a CollectionToString()
method. This method would accept an IEnumerable
and, using reflection, read a property and return a delimited string. Of course, you choose the property and delimiter.
Note that we have two versions of this method: one which accepts an IEnumerable
, the other which accepts an object. This is done to avoid the necessary typecasting in your code, since Eval()
returns everything as an object
.
public static string CollectionToString(IEnumerable collection, string property, string delimiter) { IEnumerator enumerator = collection.GetEnumerator(); if (enumerator == null || enumerator.MoveNext() == false) return String.Empty; Type type = enumerator.Current.GetType(); PropertyInfo propInfo = type.GetProperty(property); if (propInfo == null) throw new Exception(String.Format("Property '{0}' not found in collection", property)); StringBuilder output = new StringBuilder(); output.Append(propInfo.GetValue(enumerator.Current, null).ToString()); while (enumerator.MoveNext()) { output.Append(delimiter); output.Append(propInfo.GetValue(enumerator.Current, null).ToString()); } return output.ToString(); } public static string CollectionToString(object collection, string property, string delimiter) { return CollectionToString(collection as IEnumerable, property, delimiter); }
This method — which I typically apply to a StringHelper
class whose namespace is added to my web.config (more on that another day) — can replace the Repeater code above as follows.
<!-- you must first expose the collection to the ASPX page as a public property --> < %= StringHelper.CollectionToString("ListOfStates", "Name", ", ") %>
A similar method could be added to a helper class in Castle MonoRail to do the same without using foreach
loops in your view.