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#.