You want to combine strings in your C# program using the string.Join static method. This allows you to easily divide parts of an output string with commas or other delimiters. string
Static method. Here we note that string.Join in C# is a static method, meaning it does not need to be called on an instance of string. It concatenates strings together with a separator string in between them.
ToString UsageTrimEnd, Removing Trailing Chars
msdn.microsoft.com
ArgumentNullExceptionArgumentOutOfRangeExceptionOutOfMemoryException
Join String List
Use string.Join
Here we see a basic example of how you can combine strings in an array or List into a new single string with dividing characters in it. The example that follows will produce the output with separating commas.Program that joins strings [C#] using System; class Program { static void Main() { string[] arr = { "one", "two", "three" }; Console.WriteLine(string.Join(",", arr)); // "string" can be lowercase, or Console.WriteLine(String.Join(",", arr)); // "String" can be uppercase } } Output one,two,three one,two,threeDescription of the example code.
Static method. Here we note that string.Join in C# is a static method, meaning it does not need to be called on an instance of string. It concatenates strings together with a separator string in between them.
HTML example
Here we see how you can use string.Join to concatenate strings of HTML. Often with HTML you need a separating tag or element, such as a <br/> tag or horizontal rule. Join solves this problem elegantly because it doesn't insert the separating tag at the end.Program that joins HTML strings [C#] using System; class Program { static void Main() { // Problem: combine these words into lines in HTML string[] dinosaurs = new string[] { "Aeolosaurus", "Deinonychus", "Jaxartosaurus", "Segnosaurus" }; // Solution: join with break tag. string html = string.Join("<br/>\r\n", dinosaurs); Console.WriteLine(html); } } Output Aeolosaurus<br/> Deinonychus<br/> Jaxartosaurus<br/> SegnosaurusDescription of the example code. There is a string[] array declared at the beginning of the code. Those strings are concatenated with Join into four lines of markup in HTML, separated by the BR tag.
string.Join versus append
String.Join is different from appending many strings together in a loop, such as with StringBuilder, because it does not insert the delimiter or separator at the end of the operation. It only inserts the delimiter in between the strings.Rewrite StringBuilder
Here we see how you can replace confusing code that appends strings in loops with much simpler string.Join code. The string.Join method is often much faster in addition to being simpler. The two methods below, CombineA and CombineB, have the same output.using System; using System.Text; class Program { static void Main() { string[] catSpecies = { "Aegean", "Birman", "Main Coon", "Nebulung" }; Console.WriteLine(CombineA(catSpecies)); Console.WriteLine(CombineB(catSpecies)); } /// <summary> /// Combine strings with commas. /// </summary> static string CombineA(string[] arr) { return string.Join(",", arr); } /// <summary> /// Combine strings with commas. /// </summary> static string CombineB(string[] arr) { StringBuilder builder = new StringBuilder(); foreach (string s in arr) { builder.Append(s).Append(","); } return builder.ToString().TrimEnd(new char[] { ',' }); } } Output Aegean,Birman,Main Coon,Nebulung Aegean,Birman,Main Coon,NebulungDescription of the example code. As noted, the two methods CombineA and CombineB both concatenate each string into a single string with separators. The species of cats are outputted as a single string. The final method shown above, CombineB, has to use the ToString() and TrimEnd() methods to convert the StringBuilder into the result.
ToString UsageTrimEnd, Removing Trailing Chars
Parameters
You can specify four parameters on string.Join, with the last two being the startIndex and the count. This overload is rarely useful in my experience, but could simplify some code.msdn.microsoft.com
Exceptions
String.Join can throw three different exceptions: ArgumentNullException, ArgumentOutOfRangeException, and OutOfMemoryException. The first two exceptions are possible quite often, and you should be ready for them. The following example shows one possible exception.ArgumentNullExceptionArgumentOutOfRangeExceptionOutOfMemoryException
Program that throws exception on Join [C#] using System; class Program { static void Main() { try { string bug = string.Join(null, null); // Null arguments are bad } catch (Exception ex) { Console.WriteLine(ex); } } } Output System.ArgumentNullException: Value cannot be null. Parameter name: valueDescription of the example code. This code demonstrates what happens when you call string.Join with null parameters. It will throw the ArgumentNullException. Depending on your application, this must be dealt with.
Join List
In real-world programs, the List collection is used frequently and it often contains strings. You can use string.Join to concatenate these strings quickly. You have to call ToArray() on your List and pass it as the second parameter to string.Join. Alternatively, you can use the generic version of string.Join; please see the distinct article.Join String List
Program that joins on List [C#] using System; using System.Collections.Generic; class Program { static void Main() { // List of cities List<string> cities = new List<string>(); cities.Add("New York"); cities.Add("Mumbai"); cities.Add("Berlin"); cities.Add("Istanbul"); // Join strings into one CSV line string line = string.Join(",", cities.ToArray()); Console.WriteLine(line); } } Output New York,Mumbai,Berlin,IstanbulDescription of the example code. The Main method first creates a List of strings, and then converts the List into a string[] array using ToArray(). string.Join returns all the strings combined into one with separators.
Benchmark
Here we test the general performance of string.Join. I wanted to see the ballpark numbers for string.Join to ensure that it doesn't cause a severe slowdown. We see that string.Join performs well and often better than loops. Please see the figures at the top of this article.Data used in benchmark string[] arr = { "one", "two", "three", "four", "five" }; Methods that were benchmarked [C#] 1000000 iterations were tested. static string CombineA(string[] arr) { return string.Join(",", arr); } static string CombineB(string[] arr) { var builder = new System.Text.StringBuilder(); foreach (string s in arr) { builder.Append(s).Append(","); } return builder.ToString(); // Has ending comma [difference] } Results string.Join: 157 ms [faster] StringBuilder Append method: 270 ms Required Join method results Input: one two three Output: one*two*threeDescription of benchmarked code. The two methods shown above, CombineA and CombineB, compare string.Join to a StringBuilder loop. They return different strings: CombineA does not have a comma at the end of its result, while CombineB does. Using TrimEnd to remove the comma makes CombineB slower.