0

如何在c#中将一个数组分成2个数组

例如,我有一个数组 [1,2,3,4,5,6,7,8,9,10] 将其分解为 [1,2,3,4,5] 和 [6,7,8, 9,10]

4

4 回答 4

4

使用 Linq

var a = new[] {1,2,3,4,5,6,7,8,9,10}
var a1 = a.Take(a.Length / 2).ToArray();
var a2 = a.Skip(a.Length / 2).ToArray();
于 2012-10-01T05:38:34.310 回答
2

使用 Linq:

var source = new int[] {1,2,3,4,5,6,7,8,9,10};
var firstHalf = source.Take(source.Length/2).ToArray();
var secondHalf = source.Skip(source.Length/2).ToArray();

Array.Copy

var source = new int[] {1,2,3,4,5,6,7,8,9,10};
var firstHalf = new int[source.Length/2];
var secondHalf = new int[source.Length - source.Length/2];
Array.Copy(source, firstHalf, firstHalf.Length];
Array.Copy(source, firstHalf.Length, secondHalf, 0, secondHalf.Length];
于 2012-10-01T05:34:38.273 回答
0

您可以使用以下方法将数组拆分为 2 个单独的数组

public void Split<T>(T[] array, int index, out T[] first, out T[] second) {
  first = array.Take(index).ToArray();
  second = array.Skip(index).ToArray();
}

public void SplitMidPoint<T>(T[] array, out T[] first, out T[] second) {
  Split(array, array.Length / 2, out first, out second);
}

用法:

int[] myArray = new int[] { 1,2,3,4,5,6,7,8,9,10 };
int[] newArray1;
int[] newArray2;

SplitMidPoint<int>(myArray, out newArray1, out newArray2);

来自:C#拆分数组

于 2012-10-01T05:33:24.900 回答
0


    public static T[] SubArray(this T[] data, int index, int length)
    {
          T[] result = new T[length];
          Array.Copy(data, index, result, 0, length);
          return result;
    }
    public void Split(T[] Source, T[] arr1,T[] arr2)
    {
         if(source.Length == 0)
         {
            arr1 = arr2 = new T[0];
            return ;
         } 
         int half = source.Length/2;
         arr1 = source.SubArray(0, half);
         arr2 = source.SubArray(half-1, half);
    } 

于 2012-10-01T05:48:33.817 回答