Dec 2 2008

ToFormattedList Extension Method

Category: Software Developmentemilioc @ 05:54

Forgive me if this incorrect, but I believe the ToFormattedList() IEnumerable extension method was part of the early ASP.NET MVC previews.  If you’ve used the method then you are aware of its usefulness.  You pass in a format string (ex. “<li>{0}</li>”) and you get back a string of all the objects that were in your IEnumerable individually formatted ("very nice" -Borat).  This is perfect if all the objects in your IEnumerable have an acceptable ToString() method. What if you are working with POCOs or business objects and you would like to use a property instead of an objects ToString() value?  This is exactly the scenario that prompted me to create a ToFormattedList() extension method for IEnumerable<T>.  

To satisfy this new requirement I needed to add a new parameter.  My version of ToFormattedList() takes a Func<T, string> parameter to access the appropriate property (we need the func, we gotta have that func).  Below is the simple code that makes this work and example of its use.

Code

    public static string ToFormattedList<T>(this IEnumerable<T> list, string format, Func<T, string> func) {
        var s = "";

        foreach (T item in list) {
            s += string.Format(format, func.Invoke(item));
        }

        return s;
    }

Usage

    var output = companies.ToFormattedList("<li>{0}</li>", c => c.Name);

Tags: , ,