TheDeveloperBlog.com


C# Concat Extension Method

Concat is an extension method. With it we take two IEnumerable collections. We then get a collection with all of the elements together. This extension method effectively concatenates sequences.


Example. In this program, we include the System.Linq namespace to get access to the Concat method. Two arrays are created upon execution of the Main method. Then we call the Concat method twice, in different orders, and display the results.

Console.WriteLine
C# program that uses Concat extension

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	int[] array1 = { 1, 3, 5 };
	int[] array2 = { 0, 2, 4 };

	// Concat array1 and array2.
	var result1 = array1.Concat(array2);
	foreach (int value in result1)
	{
	    Console.WriteLine(value);
	}
	Console.WriteLine();

	// Concat array2 and then array1.
	var result2 = array2.Concat(array1);
	foreach (int value in result2)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

1
3
5
0
2
4

0
2
4
1
3
5

Usefulness. If you have ever needed to write custom code to combine two arrays or Lists into a single one, the Concat method might be useful. Instead of the custom code, you could use call Concat.

List

Please note: This might cause some performance degradation because of the flexibility and implementation of the extension methods.

Extension Method

Summary. Much like string.Concat concatenates strings, the Concat extension concatenates sequences or collections. Whenever we need to combine two arrays into a third array, we use the Concat extension method and avoid writing error-prone code.

string.Concat