.NET 2.0中是否有一个内置函数,可以将两个数组合并成一个数组?

这两个数组具有相同的类型。我从代码库中广泛使用的函数中获得这些数组,并且不能修改该函数以以不同的格式返回数据。

如果可能的话,我希望避免编写自己的函数来完成这个任务。


当前回答

这是另一种方法:

public static void ArrayPush<T>(ref T[] table, object value)
{
    Array.Resize(ref table, table.Length + 1); // Resizing the array for the cloned length (+-) (+1)
    table.SetValue(value, table.Length - 1); // Setting the value for the new element
}

public static void MergeArrays<T>(ref T[] tableOne, T[] tableTwo) {
    foreach(var element in tableTwo) {
        ArrayPush(ref tableOne, element);
    }
}

下面是代码片段/示例

其他回答

我认为你可以使用数组。收到。它有一个源索引和一个目标索引,因此您应该能够将一个数组附加到另一个数组。如果您需要更复杂的操作,而不仅仅是将一个附加到另一个,那么这个工具可能不适合您。

每个人都有自己的说法,但我认为这比“作为扩展方法使用”方法更具可读性:

var arr1 = new[] { 1, 2, 3, 4, 5 };
var arr2 = new[] { 6, 7, 8, 9, 0 };
var arr = Queryable.Concat(arr1, arr2).ToArray();

但是,它只能在将2个数组组合在一起时使用。

连接多个数组的简单代码:

string[] arr1 = ...
string[] arr2 = ...
string[] arr3 = ...    
List<string> arr = new List<string>(arr1.Length + arr2.Length + arr3.Length);
arr.AddRange(arr1);
arr.AddRange(arr2);
arr.AddRange(arr3);
string[] result = arr.ToArray();

如果你不想删除重复的,那么试试这个

使用LINQ:

var arr1 = new[] { 1, 2, 3, 4, 5 };
var arr2 = new[] { 6, 7, 8, 9, 0 };
var arr = arr1.Concat(arr2).ToArray();

创建和扩展方法来处理null

public static class IEnumerableExtenions
{
    public static IEnumerable<T> UnionIfNotNull<T>(this IEnumerable<T> list1, IEnumerable<T> list2)
    {
        if (list1 != null && list2 != null)
            return list1.Union(list2);
        else if (list1 != null)
            return list1;
        else if (list2 != null)
            return list2;
        else return null;
    }
}