Combining Arrays in C# without Duplicates: Efficient Techniques Using LINQ

Learn how to merge two arrays in C# while eliminating duplicate elements. This tutorial demonstrates efficient techniques using LINQ's `Union()` method, providing a concise and effective solution for creating a new array containing only unique elements from the input arrays.



Combining Arrays in C# without Duplicates

This article explains how to merge two arrays in C# while removing duplicate elements. The result is a new array containing only the unique elements from both input arrays.

Merging Arrays and Removing Duplicates

Merging arrays typically involves combining all elements into a single array. However, if you need to ensure uniqueness, you must remove duplicates. C#'s LINQ (Language Integrated Query) library provides a simple way to achieve this.

Using LINQ's `Union()` Method

The LINQ `Union()` method efficiently combines two sequences (like arrays) into a single sequence, removing duplicate elements. The resulting sequence contains only the unique elements from both input sequences.


var combinedArray = array1.Union(array2).ToArray();

Example 1: Combining Integer Arrays


using System;
using System.Linq;

public class CombineArrays {
    public static void Main(string[] args) {
        int[] arr1 = { 1, 2, 3, 4, 5 };
        int[] arr2 = { 3, 6, 7, 8 };
        // ... (code to combine using Union and print the result) ...
    }
}

Example 2: Combining String Arrays


using System;
using System.Linq;

public class CombineArrays {
    public static void Main(string[] args) {
        string[] arr1 = { "apple", "banana", "orange" };
        string[] arr2 = { "banana", "grape", "kiwi" };
        // ... (code to combine using Union and print the result) ...
    }
}