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"
Remember Me
Powered by: newtelligence dasBlog 2.0.7226.0
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2008, Your Name Here
E-mail