c# - How to merge two arrays

Merge two arrays
The following asp.net c# example code demonstrate us how can we merge two array objects programmatically at run time in an asp.net application. In this example code, we merge two array objects elements and create a new array object with merged elements.

.Net framework's Array Class has no any direct method or property to merge two array objects. So, we need to take help from List class. At fist, we need to initialize an empty list. Next, we can add both array's elements to the empty list.

List Class AddRange() method allow us to add the elements of the specified collection to the end of the list. So, we can add both array object's elements to the list by using List.AddRange() method as this way List.AddRange(ArrayObject). This method has a required parameter named 'collection' which represent the items collection whose elements should be added to the end of the list.

So, after adding two array object's elements to the list, we get an elements collection which contains both arrays all elements. Now, we can convert the list object to an array object by calling List.ToArray() method. The List.ToArray() method copies the elements of the list to a new array. Finally, we get an array object which elements are merged from two array objects.

<%@ Page Language="C#" AutoEventWireup="true"%>  
<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
        string[] colors = { "red", "blue", "green" };
        string[] colors2 = { "crimson", "green", "hotpink"};

        List<string> colorslist = new List<string>();

        string[] mergedcolors = colorslist.ToArray();
        Label1.Text = "Colors: ";
        foreach(string s in colors)
            Label1.Text += s + " | ";
        Label1.Text += "<br />Colors2: ";
        foreach(string s in colors2)
            Label1.Text += s + " | ";
        Label1.Text += "<br />Merged Colors: ";
        foreach (string s in mergedcolors)
            Label1.Text += s + " | ";
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - merge two arrays</title>  
    <form id="form1" runat="server">  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - merge two arrays with duplicates
        <hr width="550" align="left" color="LightBlue" />    
        <br /><br />
            Text="merge two arrays"  
More c# examples