Converting IEnumerable to a Comma-Delimited String

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.

  1. IEnumerable<long> ids = new long[]{1,3,4,5};
  2. string delimitedIds = string.Join(",", ids.Select(x => x.ToString()).ToArray());

If you need a LINQ-free version for backward compatibility, check out Missing Functions on IEnumerable on Steve Cooper’s blog.

1 Comment so far »

  1. Steve Cooper said,

    Wrote on September 2, 2008 @ 9:59 pm

    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.

Comment RSS · TrackBack URI

Leave a Comment

Name: (Required)

E-mail: (Required)

Website:

Comment: