Thursday, September 13, 2012

ConcatWith Extension Method for IEnumerable

So, I recently contributed some code to the dnpextensions project to allow easily concatenation of the contents of an IEnumerable<T> into a string using a specified separator (which defaults to a comma).  Thought I'd post it here in case anyone might find it useful:

/// <summary>
/// Concatenate a list of items using the provided separator.
/// </summary>
/// <param name="items">An enumerable collection of items to concatenate.</param>
/// <param name="separator">The separator to use for the concatenation (defaults to ",").</param>
/// <param name="formatString">An optional string formatter for the items in the output list.</param>
/// <returns>The enumerable collection of items concatenated into a single string.</returns>
/// <example>
///    <code>
///        List&lt;double&gt; doubles = new List&lt;double&gt;() { 123.4567, 123.4, 123.0, 4, 5 };
///        string concatenated = doubles.ConcatWith(":", "0.00");  // concatenated = 123.46:123.40:123.00:4.00:5.00
///     </code>
/// </example>
public static string ConcatWith<T>(this IEnumerable<T> items, string separator = ",", string formatString = "")
{
    if (items == null) throw new ArgumentNullException("items");
    if (separator == null) throw new ArgumentNullException("separator");

    // shortcut for string enumerable
    if (typeof(T) == typeof(string))
    {
        return string.Join(separator, ((IEnumerable<string>)items).ToArray());
    }

    if (string.IsNullOrEmpty(formatString))
    {
        formatString = "{0}";
    }
    else
    {
        formatString = string.Format("{{0:{0}}}", formatString);
    }

    return string.Join(separator, items.Select(x => string.Format(formatString, x)).ToArray());
}
 

No comments: