Yarl
Yarl

Reputation: 798

How to join arrays in a generic fashion way?

I want to join arrays independently of their types.

T[] arr1 = new T[];
T[] arr2 new T[];
T[] newArr = Helper.GetJoint(arr1, arr2);

Upvotes: 1

Views: 75

Answers (1)

Vikhram
Vikhram

Reputation: 4394

You can use LINQ for that

 T[] newArr = arr1.Concat(arr2).ToArray();

For larger arrays, where you want the allocation to be optimized, you can use the following extension method

public static T[] Append<T>(this ICollection<T> arr1, ICollection<T> arr2) {
    var newArr = new T[arr1.Count + arr2.Count];
    arr1.CopyTo(newArr, 0);
    arr2.CopyTo(newArr, arr1.Count);
    return newArr;
}

This can be called below

var newArr = arr1.Append(arr2);

Upvotes: 4

Related Questions