.NET 2.0中是否有一个内置函数,可以将两个数组合并成一个数组?
这两个数组具有相同的类型。我从代码库中广泛使用的函数中获得这些数组,并且不能修改该函数以以不同的格式返回数据。
如果可能的话,我希望避免编写自己的函数来完成这个任务。
.NET 2.0中是否有一个内置函数,可以将两个数组合并成一个数组?
这两个数组具有相同的类型。我从代码库中广泛使用的函数中获得这些数组,并且不能修改该函数以以不同的格式返回数据。
如果可能的话,我希望避免编写自己的函数来完成这个任务。
当前回答
只是有一个选项:如果你正在使用的数组是一个基本类型-布尔(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使用的,但这应该更快(即使只有一点点)。
其他回答
使用LINQ:
var arr1 = new[] { 1, 2, 3, 4, 5 };
var arr2 = new[] { 6, 7, 8, 9, 0 };
var arr = arr1.Union(arr2).ToArray();
请记住,这将删除重复项。如果您想保留副本,请使用Concat。
自从。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;
}
我认为你可以使用数组。收到。它有一个源索引和一个目标索引,因此您应该能够将一个数组附加到另一个数组。如果您需要更复杂的操作,而不仅仅是将一个附加到另一个,那么这个工具可能不适合您。
这是另一种方法:
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);
}
}
下面是代码片段/示例
创建和扩展方法来处理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;
}
}