RyanScottLewis
RyanScottLewis

Reputation: 14046

C# Array Merge Without Dupes

Let's say I have these two arrays:

string[] arr1 = new string[2]{"Hello", "Stack"}
string[] arr2 = new string[2]{"Stack", "Overflow"}

How would I merge them to get a third array like so: string[3]{"Hello", "Stack", "Overflow"}?

Upvotes: 15

Views: 16222

Answers (4)

Asad
Asad

Reputation: 21938

Old way of doing this

            List<string> temp = arr1.ToList<string>();
            foreach (string s in arr1)
            {
                if (!arr2.Contains(s))
                {
                    temp.Add(s);
                }
            }
            String[] arr3 = temp.ToArray<string>();  

New and better way, using .Net Framework 3.5 + LINQ

  string[] arr3 = arr1.Union(arr2).ToArray();

Upvotes: 0

malay
malay

Reputation: 1472

ar2.Union<string>(ar1, StringComparer.CurrentCultureIgnoreCase).ToArray<string>();

Upvotes: 0

kristian
kristian

Reputation: 23039

string[] arr1 = new string[2]{"Hello", "Stack"};
string[] arr2 = new string[2] { "Stack", "Overflow" };

var arr3 = arr1.Union(arr2).ToArray<string>();

Upvotes: 23

Marc Gravell
Marc Gravell

Reputation: 1064014

string[] arr3 = arr1.Union(arr2).ToArray();

(if you have LINQ and a using System.Linq; directive)

Upvotes: 2

Related Questions