15

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"}?

4 Answers 4

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

var arr3 = arr1.Union(arr2).ToArray<string>();
Sign up to request clarification or add additional context in comments.

3 Comments

Note that this requires .NET 3.5 and LINQ.
@jrista - strictly speaking, not quite true. It could be any C# 3.0 compiler targetting .NET 2.0 with (for example) LINQBridge. No .NET 3.5 requirement. And if you roll your own extension method it could go anywhere, so there would be no mention of "LINQ", even in the using directives.
@Mark: Sure, strictly speaking. However, for the average .NET programmer, I think my statement holds true and is perfectly acceptable. (I think more people would upgrade to .NET 3.5 before they choose some third-party framework like LINQBridge or roll their own in-house framework...)
2
string[] arr3 = arr1.Union(arr2).ToArray();

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

Comments

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

Comments

0

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();

1 Comment

For the "old way" ToList isn't available. Use List<string> temp = new List<string>(arr1); instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.