Of Code and Me

Somewhere to write down all the stuff I'm going to forget and then need

Convert any IEnumerable to a comma separated string of values May 25, 2010

Filed under: Uncategorized — Rupert Bates @ 1:12 pm

This extension method allows you to create a comma separated string from any IEnumerable by passing in a function which takes T and returns the string value which you are interested in:

public static string AsCommaSeparatedString<T>(this IEnumerable<T> enumerable, Func<T, string> value)
        {
            StringBuilder sb = new StringBuilder();
            foreach (T item in enumerable)
            {
                sb.Append(value(item));
                sb.Append(",");
            }
            return sb.ToString().TrimEnd(new []{','});
        }

Use it as follows:

            //get a commma separated list of usernames
            var usernames = users.AsCommaSeparatedList(u => u.Name);
Advertisements
 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s