有一个功能等价的PHP array_merge在C#

有一个功能等价的PHP array_merge在C#

问题描述:

如果没有什么创建它的最好办法

If not what's the best way to create it ?

请注意:?合并不仅是追加,它fusionned是相同的密钥

Note: merging is not just appending, it fusionned keys that are the same.

此功能列表元素的存在。数组是固定在C#中的宽度物品,所以你不能没有创建新阵列修改尺寸。然而,列表是一个不同的故事。你可以这样做:

This functionality exist on a List element. Arrays are fixed width items in C#, so you can't modify the size without creating a new array. However, Lists are a different story. You can do:

List<int> sample = oldList.AddRange(someOtherList);
// sample contains oldList with all elements of someOtherList appended to it.

此外,使用LINQ它十分容易列表和阵列之间进行转换以

Additionally, with LINQ it's trivially easy to convert between List and Array with the

.ToList()
.ToArray()

扩展方法。如果你想做到这一点与数组的一个不确定的数字,你可以做这样的事情:

extension methods. If you want to do that with an indeterminate number of arrays, you could do something like this:

public static class ArrayExtensions
{
     public static T[] MergeArrays<T>(this T[] sourceArray, params T[][] additionalArrays)
     {
          List<int> elements = sourceArray.ToList();

          if(additionalArrays != null)
          {
               foreach(var array in additionalArrays)
                   elements.AddRange(array.ToList());
          }

          return elements.ToArray();
     }
}

和调用:

int[] mergedArray = initialArray.MergeArrays(array1, array2, array3 /* etc */);