Generic version of string.Join

Have you ever had a list of something other than strings and wanted to combine the list in someway to get a single string? You could use string.Join if you could get your list into a string[] but that is not always so easy. Usually I end up writing my own join method.

Anyway I needed to do this earlier today and I decided to use the new C# 2.0 generics feature to write a generic version of the Join function. Here is the C# code and a sample use:

  1 // Default join that takes an IEnumerable list and just takes the ToString of each item
  2 public static string Join<T>(string separator, IEnumerable<T> list)
  3 {
  4   return Join<T>(separator, list, delegate(T o) { return o.ToString(); });
  5 }
  6 // Join that takes an IEnumerable list that uses a converter to convert the type to a string
  7 public static string Join<T>(string separator, IEnumerable<T> list, Converter<T, string> converter)
  8 {
  9   StringBuilder sb = new StringBuilder();
 10   foreach (T t in list)
 11   {
 12     if (sb.Length != 0) sb.Append(separator);
 13     sb.Append(converter(t));
 14   }
 15   return sb.ToString();
 16 }
 17 static void Main(string[] args)
 18 {
 19   List<int> list = new List<int>();
 20   list.AddRange(new int[] { 10, 20, 30, 40, 50 });
 21 
 22   // Just take the ToString of each integer in the list
 23   Console.WriteLine(Join(" ", list));
 24   // Use an anonymous method to convert each integer to its hex value
 25   Console.WriteLine(Join(" ", list, delegate(int i) { return i.ToString("X"); }));
 26 }

Output:
10 20 30 40 50
A 14 1E 28 32

Hopefully this will be a handy little example for someone on how to use generics and anonymous methods in C#.

2 Comments

  • Dim attrList As List(Of String) = New List(Of String)
    attrList.Add("Val1")
    attrList.Add("Val2")
    retVal = String.Join(", ", attrList.ToArray())

  • Actually both Join methods would be better implemented using the Type Object instead of a generic type T.

    The reason behind that is, that only .ToString() is used in the generic type, which is implemented in object.

    Checking a generic type against null will cause boxing, and using that in a foreach loop on items in a list will cause a lot boxing for big lists. So you can directly use Object and avoid the boxing process for every item in the list that is done in the delegate by checking for a null value.

    So directly using object is a lot faster.

Comments have been disabled for this content.