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

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

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


当前回答

试试这个:

ArrayLIst al = new ArrayList();
al.AddRange(array_1);
al.AddRange(array_2);
al.AddRange(array_3);
array_4 = al.ToArray();

其他回答

string[] names1 = new string[] { "Ava", "Emma", "Olivia" };
string[] names2 = new string[] { "Olivia", "Sophia", "Emma" };
List<string> arr = new List<string>(names1.Length + names2.Length);
arr.AddRange(names1);
arr.AddRange(names2);
string[] result = arr.Distinct().ToArray();
foreach(string str in result)
{
    Console.WriteLine(str.ToString());
}

Console.ReadLine();

我需要一个解决方案来组合未知数量的数组。

令人惊讶的是没有人提供一个解决方案使用SelectMany与参数。

 private static T[] Combine<T>(params IEnumerable<T>[] items) =>
                    items.SelectMany(i => i).Distinct().ToArray();

如果你不想要不同的项目,只需删除不同的项目。

 public string[] Reds = new [] { "Red", "Crimson", "TrafficLightRed" };
 public string[] Greens = new [] { "Green", "LimeGreen" };
 public string[] Blues = new [] { "Blue", "SkyBlue", "Navy" };

 public string[] Colors = Combine(Reds, Greens, Blues);

注意:使用distinct时,绝对不能保证顺序。

我想找到一种不使用数组本身以外的任何库或功能的方法。

前两个示例主要用于从头读取逻辑,但我也想知道是否会根据情况而有性能变化。

第三个例子是最实际的选择。

// Two for-loops
private static int[] MergedArrays_1(int[] a, int[] b)
{
    int[] result = new int[a.Length + b.Length];
    for (int i = 0; i < a.Length; i++)
    {
        result[i] = a[i];
    }
    for (int i = a.Length; i < result.Length; i++)
    {
        result[i] = b[i - a.Length];
    }
    return result;
}

// One for-loop
private static int[] MergedArrays_2(int[] a, int[] b)
{
    int[] results = new int[a.Length + b.Length];
    for (int i = 0; i < results.Length; i++)
    {
        results[i] = (i < a.Length) ? a[i] : b[i - a.Length];
    }
    return results;
}

// Array Method
private static int[] MergedArrays_3(int[] a, int[] b)
{
    int[] results = new int[a.Length + b.Length];
    a.CopyTo(results, 0);
    b.CopyTo(results, a.Length);
    return results;
}

最后,我做了第四个例子,可以合并多个数组,使用params关键字。

int[] result = MultipleMergedArrays(arrayOne, arrayTwo, arrayThree);
private static int[] MultipleMergedArrays(params int[][] a)
{
    // Get Length
    int resultsLength = 0;
    for (int row = 0; row < a.GetLength(0); row++)
    {
        resultsLength += a.Length;
    }

    // Initialize
    int[] results = new int[resultsLength];

    // Add Items
    int index = 0;
    for (int row = 0; row < a.GetLength(0); row++)
    {
        a[row].CopyTo(results, index);
        index += a[row].Length;
    }
    return results;
}

当使用参数时,它的工作方式是将一维数组传递到锯齿数组中。

GetLength(0)返回锯齿状数组中包含的数组数。

该代码首先计算所有数组的Length,然后根据该大小初始化一个新数组,并开始使用CopyTo()方法将整个数组添加到新的结果数组中,同时将每个添加的数组的Length添加到索引计数器中。

PS:在合并时,有时需要从数组中删除空项或某些项。

private static int[] RemoveEmpty(int[] array)
{
    int count = 0;
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i] == 0) count++;
    }

    int[] result = new int[array.Length - count];

    count = 0;
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i] == 0) continue;
        result[count] = array[i];
        count++;
    }

    return result;
}

这个函数可以与上面的函数结合使用。

它接受一个数组,计算匹配为0的项的数量。并创建一个大小合适的新数组。然后计数器被回收并用作索引,用于将输入数组的值放入新的更小的结果数组中。 当一个项匹配0时,它将跳过该循环中的其余代码,并继续下一轮循环,不增加整数计数器。

这段代码将适用于所有情况:

int[] a1 ={3,4,5,6};
int[] a2 = {4,7,9};
int i = a1.Length-1;
int j = a2.Length-1;
int resultIndex=  i+j+1;
Array.Resize(ref a2, a1.Length +a2.Length);
while(resultIndex >=0)
{
    if(i != 0 && j !=0)
    {
        if(a1[i] > a2[j])
        {
            a2[resultIndex--] = a[i--];
        }
        else
        {
            a2[resultIndex--] = a[j--];
        }
    }
    else if(i>=0 && j<=0)
    { 
        a2[resultIndex--] = a[i--];
    }
    else if(j>=0 && i <=0)
    {
       a2[resultIndex--] = a[j--];
    }
}

自从。net 5以来,我们现在有了AllocateUnitializedArray,它可能会为建议的解决方案增加额外的(小)性能改进:

public static T[] ConcatArrays<T>(IEnumerable<T[]> arrays)
{
    var result = GC.AllocateUnitializedArray<T>(arrays.Sum(a => a.Length));
    var offset = 0;
    foreach (var a in arrays)
    {
        a.CopyTo(result, offset);
        offset += a.Length;
    }
    return result;
}