OneBite.Dev - Coding blog in a bite size

Find The Union Of Two Arrays In C#

Code snippet for how to Find The Union Of Two Arrays In C# with sample and detail explanation

Combining or finding the union of two arrays is a common operation in data processing. This article aims to provide a simple guide concerning how you can implement this in C#, complete with a code snippet and step-by-step explanation.

Code snippet: Finding the Union of Two Arrays

using System; 
using System.Linq; 

public class Program
{
    public static void Main(string[] args)
    {
        int[] array1 = { 1, 2, 3, 4, 5 };
        int[] array2 = { 3, 4, 5, 6, 7 };

        var union = array1.Union(array2);

        foreach (var value in union)
        {
          Console.Write("{0} ", value);
        }
            
    }
}

Code Explanation: Finding the Union of Two Arrays

Let’s break down what is happening in the code above step by step:

  1. Namespaces: The first two lines are namespaces that are required for this code to function. The System namespace contains fundamental classes and base classes that define commonly-used values and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. The System.Linq namespace provides classes and interfaces that support queries that use Language-Integrated Query (LINQ). The .Union() method we use later is a part of the System.Linq namespace.

  2. Class Declaration: public class Program here we are declaring a class named Program. In C#, public is an access modifier, which denotes that the class Program can be accessed from anywhere.

  3. Method Declaration: The Main method is the entry point of the C# console application. The string[] args parameter in the Main method is used for command line arguments.

  4. Array Initialization: int[] array1 = { 1, 2, 3, 4, 5 }; int[] array2 = { 3, 4, 5, 6, 7 }; Two integer arrays are defined, array1 and array2.

  5. Finding Union: var union = array1.Union(array2); The Union() method is invoked on the array1 and array2. This method returns a new array that includes distinct elements from both the arrays.

  6. Display Output: The final block of code is a foreach loop that iterates over each element in the union array and outputs it.

Thus, when the above program is compiled and executed, it produces the union of array1 and array2, and displays it. The output of the given program would be 1, 2, 3, 4, 5, 6, 7.

c-sharp