How to combine two arrays without duplicate values in C#?


Learn how to combine two arrays without duplicate values in C# using the Union() method.

Example: Combine String Arrays
string[] animals = { "Cat", "Alligator", "Fox", "Donkey", "Cat" };
string[] birds = { "Sparrow", "Peacock", "Dove", "Crow" };
 
var all = animals.Union(birds).ToArray();

In the same way, use the Union() method with the number array.

Example:
int[] num1 = { 1, 2, 3, 4, 3, 55, 23, 2 };           
int[] num2 = { 55, 23, 45, 50, 80 };
 
var all = num1.Union(num2).ToArray();

If an array contains objects of a custom class, then you need to implement IEquatable<T> or IEqualityComparer<T>, as shown below.

Example: Implement IEquatable
class Person : IEquatable<Person>
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
 
    public bool Equals(Person other)
    {
        return FirstName.Equals(other.FirstName) && LastName.Equals(other.LastName);
    }
 
    public override int GetHashCode()
    {
        return Id.GetHashCode() ^ (FirstName == null ? 0 : FirstName.GetHashCode()) ^ (LastName == null ? 0 : LastName.GetHashCode());
    }
}

Now, you can use the Union() method, as shown below.

Example: Combine Object Arrays
Person[] people1 = {
        new Person(){ FirstName="Steve", LastName="Jobs"},
        new Person(){ FirstName="Bill", LastName="Gates"},
        new Person(){ FirstName="Steve", LastName="Jobs"},
        new Person(){ FirstName="Lary", LastName="Page"}
    };
 
    Person[] people2 = {
        new Person(){ FirstName="Steve", LastName="Jobs"},
        new Person(){ FirstName="Lary", LastName="Page"},
        new Person(){ FirstName="Bill", LastName="Gates"}
    };
    
var allp = people1.Union(people2).ToArray();
Array.ForEach(allp, p => Console.WriteLine(p.FirstName));