C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
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.
Please note: This might cause some performance degradation because of the flexibility and implementation of the extension methods.
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.