Merging Two Arrays in .Net

Merging two arrays in .NET

If you can manipulate one of the arrays, you can resize it before performing the copy:

T[] array1 = getOneArray();
T[] array2 = getAnotherArray();
int array1OriginalLength = array1.Length;
Array.Resize<T>(ref array1, array1OriginalLength + array2.Length);
Array.Copy(array2, 0, array1, array1OriginalLength, array2.Length);

Otherwise, you can make a new array

T[] array1 = getOneArray();
T[] array2 = getAnotherArray();
T[] newArray = new T[array1.Length + array2.Length];
Array.Copy(array1, newArray, array1.Length);
Array.Copy(array2, 0, newArray, array1.Length, array2.Length);

More on available Array methods on MSDN.

How do I concatenate two arrays in C#?


var z = new int[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);

Merge two arrays and return sorted array in c#

Solution without linq:

int[] array1 = new int[] { 3, 5, 6, 9, 12, 14, 18, 20, 25, 28 };
int[] array2 = new int[] { 30, 32, 34, 36, 38, 40, 42, 44, 46, 48 };

int count1 = array1.Length;
int count2 = array2.Length;
int[] arrayResult = new int[count1 + count2];

int a = 0, b = 0; // indexes in origin arrays
int i = 0; // index in result array

// join
while (a < count1 && b < count2)
{
if (array1[a] <= array2[b])
{
// element in first array at current index 'a'
// is less or equals to element in second array at index 'b'
arrayResult[i++] = array1[a++];
}
else
{
arrayResult[i++] = array2[b++];
}
}

// tail
if (a < count1)
{
// fill tail from first array
for (int j = a; j < count1; j++)
{
arrayResult[i++] = array1[j];
}
}
else
{
// fill tail from second array
for (int j = b; j < count2; j++)
{
arrayResult[i++] = array2[j];
}
}

// print result
Console.WriteLine("Result is {{ {0} }}", string.Join(",", arrayResult.Select(e => e.ToString())));

Result:

{ 3,5,6,9,12,14,18,20,25,28,30,32,34,36,38,40,42,44,46,48 }

Graphical explanation:

Merge

Merge two string arrays in .NET/C# 2.0?

From this answer:

var z = new string[x.length + y.length];
x.CopyTo(z, 0);
y.CopyTo(z, x.length);

Merging two arrays without any duplicates [VB.NET]

LINQ would be the easiest way to go here:

Dim combinedUniqueNames = names1.Union(names2).Distinct().ToArray()

Union will combine two lists, Distinct will remove duplicates and ToArray creates a new array from the result. As is pretty much always the case with LINQ extension methods, they can all be called on any IEnumerable(Of T). Your String arrays implement IEnumerable(Of String).

EDIT:

As per Jimi's comment, we just need:

Dim combinedUniqueNames = names1.Union(names2).ToArray()

I guess I should have realised, given that 'union' is a set operation and does exclude duplicates in a mathematical context.

How to merge three arrays in visual basic?

I'd just concatenate and sort them with LINQ:

Dim arr4 = arr.Concat(arr2).Concat(arr3).OrderBy(Function(x) x)

Whether or not you call .ToArray() is optional and depends what you do with arr4. If you will enumerate it with a foreach loop you can leave it like above. If you will random access it or pass it round as an array of int then call ToArray on it

Make sure you Imports System.Linq


If you don't want to use LINQ, a simple loop:

Dim arr4() as New Integer(arr.Length * 3 - 1)

For x = 0 to arr.Length - 1 Step 1
arr4(3*x) = arr(x)
arr4(3*x+1) = arr2(x)
arr4(3*x+2) = arr3(x)
Next x

This works completely differently - the LINQ version would have made an array of 1 4 7 2 5 8 3 6 9 and then sorted it, this one puts the bits in the right order naturally, but if your data didn't sort this way the two approaches would produce different outputs!

Merge two arrays in a Key = Value

LINQ has a little-known function to do just that - Zip. The function takes two collections and merges them into a single collection:

int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };

var numbersAndWords = numbers.Zip(words, (number, word) => new KeyValuePair<string,int>(word, number);

Joining/merging arrays in C#

That's very inefficent at the moment - all those calls to ElementAt could be going through the whole sequence (as far as they need to) each time. (It depends on the implementation of the sequence.)

However, I'm not at all sure I even understand what this code is doing (using foreach loops would almost certainly make it clearer, as would iterating forwards instead of backwards. Could you give some sample input? and expected outputs?

EDIT: Okay, I think I see what's going on here; you're effectively pivoting valueCollections. I suspect you'll want something like:

static Dictionary<int, string[]> MergeArrays(
IEnumerable<int> idCollection,
params IEnumerable<string>[] valueCollections)
{
var valueCollectionArrays = valueCollections.Select
(x => x.ToArray()).ToArray();
var indexedIds = idCollection.Select((Id, Index) => new { Index, Id });

return indexedIds.ToDictionary(x => Id,
x => valueCollectionArrays.Select(array => array[x.Index]).ToArray());
}

It's pretty ugly though. If you can make idCollection an array to start with, it would frankly be easier.

EDIT: Okay, assuming we can use arrays instead:

static Dictionary<int, string[]> MergeArrays(
int[] idCollection,
params string[][] valueCollections)
{
var ret = new Dictionary<int, string[]>();
for (int i=0; i < idCollection.Length; i++)
{
ret[idCollection[i]] = valueCollections.Select
(array => array[i]).ToArray();
}
return ret;
}

I've corrected (hopefully) a bug in the first version - I was getting confused between which bit of the values was an array and which wasn't. The second version isn't as declarative, but I think it's clearer, personally.



Related Topics



Leave a reply



Submit