OneBite.Dev - Coding blog in a bite size

Find The Unique Elements In Two Arrays In C#

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

There are times in programming when you might need to find the unique elements in two different arrays. This article will illustrate a simple way to achieve this in C# language using a straightforward code snippet.

Code snippet: Finding Unique Elements in Two Arrays

Here is a simple implementation:

using System;
using System.Linq;

class Program
{
   static void Main()
   {
     // Define our inputs
     int[] array1 = {1, 2, 3, 4, 5};
     int[] array2 = {3, 4, 5, 6, 7};

     // Find the unique elements
     int[] uniqueElements = array1.Concat(array2)
                                  .Distinct()
                                  .ToArray();
 
    // Display the result
    foreach(int i in uniqueElements)
    {
        Console.Write(i + " ");
    }
    Console.ReadLine();
  }
}

This code, when run, will output: 1 2 3 4 5 6 7

Code Explanation: Finding Unique Elements in Two Arrays

Let’s analyze the code snippet step by step and understand how it works.

First, we define two integer arrays, array1 and array2, that contain the numbers that we want to compare.

Next, we use the Concat() method from the System.Linq namespace to combine array1 and array2. This will create a third array that carries all elements of the first two arrays.

int[] uniqueElements = array1.Concat(array2)...

Then, we use the Distinct() method, which is also part of the System.Linq namespace. This method removes duplicate values from an array, leaving only the unique values.

...Distinct()...

Finally, we convert the object back into an array to make it easy to work with.

...ToArray();

Using a foreach loop, we iterate over each element in the uniqueElements array and print them out.

This gives us an array of unique values from both array1 and array2, effectively finding and displaying the unique elements in two arrays.

By using the power of LINQ, we achieve this with minimal code, focusing on just the key operations, and clearly expressing the solution to the problem at hand. This is the core strength and beauty of using C# and LINQ for such operations.

c-sharp