C# Join

Join objects together

The string.Join method combines many strings into one. It receives two arguments: an array or IEnumerable and a separator string. It places the separator between every element of the collection in the returned string.

Example

String

First, we combine string elements from an array into a new, single string with dividing characters. This example will produce the output with separating commas. The output data type is a string.

String Array

Note:Join is a static method.
We need no string instance to call it.
We just use the string class.

Static Method
Program that joins strings: C#

using System;

class Program
{
    static void Main()
    {
	string[] arr = { "one", "two", "three" };

	// "string" can be lowercase.
	Console.WriteLine(string.Join(",", arr));

	// ... "String" can be uppercase.
	Console.WriteLine(String.Join(",", arr));
    }
}

Output

one,two,three
one,two,three
Array

The first line in Main declares a new string array with three elements. The second two lines display the result of String.Join to the screen. You can use uppercase or lowercase String. You do not need to specify a string instance.

Parameters:You can specify four arguments on string.Join. The last two are the startIndex and the count.

Note:This overload is rarely useful in my experience, but could simplify some code.

Overload

HTML

Plus

We 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 helps because it doesn't insert the separating tag at the end.

Next:The strings are concatenated with Join into four lines of markup in HTML, separated by the BR tag.

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/>
Segnosaurus

StringBuilder

Letters of the alphabet: ABC

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

Note:CombineA combines strings with Join. CombineB combines strings with StringBuilder and its Append method.

Program that combines strings with Join: C#

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,Nebulung
Note

In this example, the two methods CombineA and CombineB both concatenate each string into a single string with separators. The final method, CombineB, has to use ToString and TrimEnd to convert the StringBuilder into the result.

ToString: StringBuilderTrimEnd

Comparison. String.Join is different from appending many strings together in a loop, such as with StringBuilder—it does not insert the delimiter at the end. Instead it only inserts the delimiter in between the strings.

Exceptions

Error

String.Join can throw three different exceptions. The first two exceptions (ArgumentNullException, ArgumentOutOfRangeException) are often possible. The following example shows one possible exception.

ArgumentNullExceptionArgumentOutOfRange ExceptionOutOfMemoryException
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: value
Null keyword

This code shows what happens when you call string.Join with null parameters. It will throw an ArgumentNullException. Depending on your application, this must be dealt with using exception handling.

Exception

List

List

It is possible to join a List generic. Please note that this example includes the System.Collections.Generic namespace. In the Main entry point, a List is instantiated with three string literals in it.

ListString Literal

Next, the string.Join<string> method is invoked. The first argument indicates the separator. The second argument is a reference to the List instance. The method returns a joined string containing the separator.

Programming tip

Tip:By using this version of the string.Join<string> method, you can reduce copies of your collection before joining.

And:For this reason, it is preferable to use this version on your List if you do not have an array of your strings handy.

Program that joins List of strings: C#

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	// Create a List of three strings.
	var list = new List<string>() { "cat", "dog", "rat" };
	// Join the strings from the List.
	string joined = string.Join<string>("*", list);
	// Display.
	Console.WriteLine(joined);
    }
}

Output

cat*dog*rat

Benchmark

Performance

Continuing on, 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—often better than loops.

Data used in benchmark: C#

string[] arr = { "one", "two", "three", "four", "five" };

Methods that were benchmarked, 1000000 iterations: C#

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*three
Piece of computer software: a program

The two methods, 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.

StringBuilderForeach

Thus:We find that using the TrimEnd method to remove the comma makes CombineB slower.

Summary

Join is an important operation on the string type. It simplifies certain common operations on string arrays. We created comma-separated values and generated HTML source. And string.Join has excellent performance for common usages.


C#: String