c# - How to merge two arrays without duplicates

Merge two Arrays without duplicates
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can merge two Arrays without duplicates. That means we will merge two Array instances elements without duplicating value. We only take unique elements while merging two Array objects. In this .net c# example code, we will use Enumerable Union() method.

The Enumerable Union() method produces the set union of two sequences. The Enumerable Union<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) method overload produces the set union of two sequences by using the default equality comparer. There are two parameters named first and second.

The first parameter is an IEnumerable<T> whose distinct elements are from the first set for the union. And the second parameter is also an IEnumerable<T> whose distinct elements are from the second set for the union.

The method overload returns an IEnumerable<T> that contains the elements from both input sequences, excluding duplicates. It throws ArgumentNullException if the first or second parameter value is null.

The Enumerable ToArray() method creates an array from an IEnumerable<T>. So using the Enumerable ToArray() method we can create an Array object again from the Union() method returned sequence.

So finally, using this Enumerable Union() method we can merge two Arrays without duplicates.

<%@ 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"};
        var mergedcolors = colors.Union(colors2);

        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# linq union example - array merge without duplicates</title>  
    <form id="form1" runat="server">  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# linq union example - array merge without duplicates
        <hr width="550" align="left" color="LightBlue" />    
        <br /><br />
            Text="array merge without duplicates"  
More c# examples