How to concatenate two arrays in C#

How to concatenate two arrays in C#

In this post we will give you information about How to concatenate two arrays in C#. Hear we will give you detail about How to concatenate two arrays in C#And how to use it also give you demo for it if it is necessary.

we are going to learn about how to concatenate the two arrays in C# with the help of examples.

Concatenation means the joining of two or more arrays into a single array.

Consider, we have the following two arrays:

int[] array1 = { 1, 2, 3 };int[] array2 = { 4, 5, 6 };

Now, we need to join above two arrays like this:

[1, 2, 3, 4, 5, 6]

Using Enumerable.Concat() method

To concatenate the two arrays into a single array, we can use the Enumerable.Concat() method in C#.

Note: The Enumberable.Concat() is available in System.Linq namespace.

Here is an example:

using System;using System.Linq;class ConcatenateArrays {  static void Main() {   int[] array1 = { 1, 2, 3 };   int[] array2 = { 4, 5, 6 };   int[] result = array1.Concat(array2).ToArray();   Console.WriteLine(String.Join(",", result));  }}

Output:

[1, 2, 3, 4, 5, 6]

Using AddRange() method

Similarly, we can use the AddRange() method in C# to join two arrays into a single array.

Example:

using System;using System.Collections.Generic;class ConcatenateArrays {  static void Main() {      int[] arr1 = {1, 2, 3};      int[] arr2 = {4, 5, 6};      var myList = new List<int>();      myList.AddRange(arr1);      myList.AddRange(arr2);      int[] result = myList.ToArray();   Console.WriteLine(String.Join(",", result));  }}

In the above code, we have first initialized an empty integer List and then added arr1 and arr2 to the List using the AddRange() method, at the end we have converted a list to an array using ToArray() method.

Hope this code and post will helped you for implement How to concatenate two arrays in C#. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US