Wednesday, April 2, 2008

Fuse Extension Method

Previously, a few of us held a discussion about the best way to concatinate a number of string array elements into a single string. You can find details here. Last week, I needed something a bit more general purpose. Came up with an extension method on IEnumerable that will accomplish this for any type.

public static string Fuse<TSource>(this IEnumerable<TSource> source, string separator)
    if (source is string[])
        return string.Join(separator, source as string[]);

    return source.Aggregate(new StringBuilder(),
        (sb, n) => sb.Length == 0 ? sb.Append(n) : sb.Append(separator).Append(n),
        sb => sb.ToString());

The method is optimized to use the string.Join method when the underlying type is a string. Join uses unsafe code and is very quick. Here are a few example uses:

string[] names = new string[] { "Andy", "Wayne", "Dina", };
string allNames = names.Fuse(", ");  // "Andy, Wayne, Dina"

int[] numbers = new int[] { 1, 2, 3, 4, 5, };
string allNumbers = numbers.Fuse(":"); // "1:2:3:4:5"

object[] objects = new object[] { 1, "ten", 5.5, true, false, };
string allObjects = objects.Fuse("/"); // "1/ten/5.5/True/False"

No comments:

Post a Comment