将数组拆分为2个数组C#

时间:2012-05-22 10:50:04

标签: c# arrays linq

编辑:我尝试过Take / Skip方法,但收到以下错误:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<string>' to   
'string[]'. An explicit conversion exists (are you missing a cast?)

我不知道我做错了什么,因为我复制了赛义德的代码。

我有一个字符串数组(包含20到300个项目),我想将它从第一个数组的中间拆分为2个独立的数组。

我知道如何使用for循环来实现这一点,但我想知道是否有更快/更好的方法。我还需要能够正确地分割数组,即使它具有奇数个项目,例如:

string[] words = {"apple", "orange", "banana", "pear", "lemon"};
string[] firstarray, secondarray;
SplitArray(words, out firstarray, out secondarray); // Or some other function
// firstarray has the first 3 of the items from words, 'apple', 'orange' and 'banana'
// secondarray has the other 2, 'pear' and 'lemon'

7 个答案:

答案 0 :(得分:48)

您可以使用linq:

firstArray = array.Take(array.Length / 2).ToArray();
secondArray = array.Skip(array.Length / 2).ToArray();

为什么这样可行,尽管原始数组大小相同?

firstArray采用array.Length / 2个元素,第二个元素跳过第一个array.Length / 2元素,这意味着这两个数组之间没有任何冲突。当然,如果元素的数量是奇数,我们不能将数组分成两个相等大小的部分。

如果你想在前半部分有更多元素(在奇数情况下),请执行以下操作:

firstArray = array.Take((array.Length + 1) / 2).ToArray();
secondArray = array.Skip((array.Length + 1) / 2).ToArray();

答案 1 :(得分:5)

string[] words = {"apple", "orange", "banana", "pear", "lemon"};
int mid = words.Length/2;
string[] first = words.Take(mid).ToArray();
string[] second = words.Skip(mid).ToArray();

答案 2 :(得分:4)

一种更通用的方法,将其分割为您指定的任意数量的部分:

public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
        {
          return list.Select((item, index) => new {index, item})
                       .GroupBy(x => (x.index + 1) / (list.Count()/parts) + 1)
                       .Select(x => x.Select(y => y.item));
        }

*编辑谢谢skarmats

答案 3 :(得分:4)

如果您不想/不能使用LINQ,您可以这样做:

    string[] words = { "apple", "orange", "banana", "pear", "lemon" };
    string[] firstarray, secondarray;
    int mid = words.Length / 2;
    firstarray = new string[mid];
    secondarray = new string[words.Length - mid];
    Array.Copy(words, 0, firstarray, 0, mid);
    Array.Copy(words, mid, secondarray, 0, secondarray.Length);

答案 4 :(得分:3)

您可以使用范围表示法轻松实现这一点:

var x = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
var pivot = x.Length / 2;
var p1 = x[..pivot];
var p2 = x[pivot..];

答案 5 :(得分:2)

string[] words = { "apple", "orange", "banana", "pear", "lemon" };
var halfWay = words.Length/2;

var firstHalf = words.Take(halfWay);
var secondHalf = words.Skip(halfWay);

答案 6 :(得分:-1)

以防万一有人想改用函数:

>>> import numpy as np
>>> a=np.array([1,2,3,4,5,6,7,8,9,10])
>>> a.shape
(10,)
>>> a=a.reshape(1,10,1)
>>> a.shape
(1, 10, 1)
>>> a=a[0]
>>> a.shape
(10, 1)