Thursday, March 16, 2006

Concatenate Generic String List To A String

How to convert .NET 2.0 Generic List<string> to a string like "str1, str2,..."? Of course we can loop through each items inside the generic list, and add each to a string builder. But that doesn't look very elegant. The easier way is use string.Join static method and Generic ToArray method:
using System;
using System.Collections.Generic;

class Program
{
static void Main(string[] args)
{
List<string> Names = new List<string>();
Names.Add("Bob");
Names.Add("Rob");
string strNames = string.Join(", ", Names.ToArray());
Console.WriteLine(strNames);
Console.Read();
}
}
The result is:
Bob, Rob