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"


Popular posts from this blog

Yet once more into the breech (of altered programming logic)

Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

How to convert SVG data to a Png Image file Using InkScape