TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Concat Extension Method

This C# example program uses the Concat extension method from System.Linq.

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


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf