如何以通用方式联接数组?

时间:2019-02-25 17:11:21

标签: c# arrays concat

我想独立于数组类型加入数组。

 func moveZeroes(_ nums: inout [Int]) {
    var index = 0
    for (i,n) in nums.enumerated()
    {
        if n != 0
        {
            nums[index] = n
            index += 1
        }

    }

    while index < nums.count
    {
        nums[index] = 0
        index += 1
    }
}

2 个答案:

答案 0 :(得分:4)

您可以为此使用LINQ

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

对于较大的阵列,要在其中优化分配,可以使用以下扩展方法

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;
}

可以在下面称为

var newArr = arr1.Append(arr2);

答案 1 :(得分:1)

1。绝对可以指望Array.CopyTo

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

2。 If one is satisfied just with unmanaged types…

public static bool GetArraysJoint2<T>(T[] array1, T[] array2, out T[] joint, out Exception e)
{
    try
    {
        int length = checked(array1.Length + array2.Length);
        joint = new T[length];
    }
    catch (Exception _e) when (_e is OverflowException || _e is OutOfMemoryException)
    {
        e = _e;
        joint = null;
        return false;
    }

    array1.CopyTo(joint, 0);
    array2.CopyTo(joint, array1.Length);

    e = null;
    return true;
}

3。最简单的方法– LINQ

public static bool GetArraysJoint<T>(T[] array1, T[] array2, out T[] joint, out Exception e) where T : unmanaged
{
    try
    {
        int length = checked(array1.Length + array2.Length);
        joint = new T[length];
    }
    catch (Exception _e) when (_e is OverflowException || _e is OutOfMemoryException)
    {
        e = _e;
        joint = null;
        return false;
    }

    int
        array1ByteLength,
        array2ByteLength;

    unsafe
    {
        array1ByteLength = array1.Length * sizeof(T);
        array2ByteLength = array2.Length * sizeof(T);
    }

    Buffer.BlockCopy(array1, 0, joint, 0, array1ByteLength);
    Buffer.BlockCopy(array2, 0, joint, array1ByteLength, array2ByteLength);

    e = null;
    return true;
}