If not what's the best way to create it ?
Note: merging is not just appending, it fusionned keys that are the same.
If not what's the best way to create it ?
Note: merging is not just appending, it fusionned keys that are the same.
You can use the LINQ Concat()
method:
using System.Linq;
// ...
var arr1 = new[] { 1, 2, 3 };
var arr2 = new[] { 4, 5, 6 };
var merged = arr1.Concat(arr2); // This returns an IEnumerable<int>
// If you want an actual array, you can use:
var mergedArray = merged.ToArray();
This functionality exist on a List element. Arrays are fixed width items in C#, so you can't modify the size without creating a new array. However, Lists are a different story. You can do:
List<int> sample = oldList.AddRange(someOtherList);
// sample contains oldList with all elements of someOtherList appended to it.
Additionally, with LINQ it's trivially easy to convert between List and Array with the
.ToList()
.ToArray()
extension methods. If you want to do that with an indeterminate number of arrays, you could do something like this:
public static class ArrayExtensions
{
public static T[] MergeArrays<T>(this T[] sourceArray, params T[][] additionalArrays)
{
List<int> elements = sourceArray.ToList();
if(additionalArrays != null)
{
foreach(var array in additionalArrays)
elements.AddRange(array.ToList());
}
return elements.ToArray();
}
}
And call:
int[] mergedArray = initialArray.MergeArrays(array1, array2, array3 /* etc */);
Duplicate. Already discussed here:
Most efficient way to append arrays in C#?
You can't merge arrays as arrays have fixed size in C#. There are numerous ways to do this with enumerables and List.
No not directly equivalent to array_merge.
If you just want to merge two arrays there is already another question : Merging two arrays in .NET
If your looking for a direct array merge replacement there is none.