C# Code

String Join Example

Did you know you can use String.Join to append together a number of strings with a delimiter without a loop?

-- Lee

const string delimiter = ",";

var animals = new List<string>
{
	"Dog",
	"Cat",
	"Lion",
	"Badger",
	"Elephant"
};
		   
// Build up string using Stringbuilder and a loop
var builder = new StringBuilder();
foreach (var animal in animals)
{
	builder.AppendFormat("{0}{1}", animal, delimiter);
}

// Outputs "Dog,Cat,Lion,Badger,Elephant,"
Console.WriteLine(builder.ToString());

// Build up string using String.Join
// The added benefit of String.Join is that it doesn't have a trailing comma
var commaDelimited = String.Join(delimiter, animals);

// Outputs "Dog,Cat,Lion,Badger,Elephant"
Console.WriteLine(commaDelimited);