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

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

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


当前回答

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

令人惊讶的是没有人提供一个解决方案使用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时,绝对不能保证顺序。

其他回答

首先,一定要问自己一个问题:“我真的应该在这里使用数组吗?”

除非您正在构建速度最重要的东西,否则类型化的List,如List<int>可能是最好的方法。我唯一一次使用数组是在通过网络发送东西时使用字节数组。除此之外,我从不碰它们。

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

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

创建和扩展方法来处理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;
    }
}

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

令人惊讶的是没有人提供一个解决方案使用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时,绝对不能保证顺序。

只是有一个选项:如果你正在使用的数组是一个基本类型-布尔(bool), Char, SByte, Byte, Int16(短),UInt16, Int32 (int), UInt32, Int64(长),UInt64, IntPtr, UIntPtr,单,或双-那么你可以(或应该?)尝试使用Buffer.BlockCopy。根据Buffer类的MSDN页面:

与系统中的类似方法相比,这个类在操作基元类型方面提供了更好的性能。数组类。

使用@OwenP回答中的c# 2.0示例作为起点,它将如下所示:

int[] front = { 1, 2, 3, 4 };
int[] back = { 5, 6, 7, 8 };

int[] combined = new int[front.Length + back.Length];
Buffer.BlockCopy(front, 0, combined, 0, front.Length);
Buffer.BlockCopy(back, 0, combined, front.Length, back.Length);

Buffer之间在语法上几乎没有任何区别。BlockCopy和Array。复制@OwenP使用的,但这应该更快(即使只有一点点)。