I’m not sure whether it’s the fastest way to convert an enumerable collection of longs or ints to a comma-delimited list in C#, but it might be the shortest.
If you need a LINQ-free version for backward compatibility, check out Missing Functions on IEnumerable on Steve Cooper’s blog.
1 Comment
Steve Cooper
Hi. Thanks for the mention! I’ve found that Join is so useful on IEnumerable, I’ve written an extension function which has this signature;
string Join(this IEnumerable sequence, string seperator);
which means you can write;
string delimitedids = ids.Select(x => x.ToString()).Join(“, “);
Here’s the implementation using a stringbuilder;
public static string Join(this IEnumerable strings, string seperator)
{
IEnumerator en = strings.GetEnumerator();
StringBuilder sb = new StringBuilder();
if (en.MoveNext())
{
// we have at least one item.
sb.Append(en.Current);
}
while (en.MoveNext())
{
// second and subsequent get delimiter
sb.Append(seperator).Append(en.Current);
}
return sb.ToString();
}
I tend to use this all the time when putting together code that generates descriptions; debug messages, ToStrings, that kind of thing.
02 Sep 2008 09:09 pm
Leave a Comment