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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10700529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:53:27  来源:igfitidea点击:

Splitting an array into 2 arrays C#

c#arrayslinq

提问by matthewr

Edit: I have tried the Take/Skip method but I get the following error:

编辑:我尝试了 Take/Skip 方法,但出现以下错误:

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

I do not know what I am doing wrong because I copied Saeed's code.

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

I have a string array (containing anywhere from 20 to 300 items) and I want to split it into 2 separate arrays, from the middle of the first one.

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

I know how I can do this using a for loop but I would like to know if there was a faster/better way of doing it. I also need to be able to correctly split an array even if it has an odd number of items, eg:

我知道如何使用 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'

采纳答案by Saeed Amiri

You can use linq:

您可以使用 linq:

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

Why this works, despite the parity of the original array size?

尽管原始数组大小的奇偶校验,为什么这有效?

The firstArray takes array.Length / 2elements, and the second one skips the first array.Length / 2elements, it means there isn't any conflict between these two arrays. Of course if the number of elements is odd we cannot split the array into two equal size parts.

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

If you want to have more elements in the first half (in the odd case), do this:

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

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

回答by Asif Mushtaq

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

回答by Nope

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

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

回答by Totero

A more generalized approach that will split it into as many parts as you specify:

一种更通用的方法,将其拆分为您指定的多个部分:

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

*Edited Thanks skarmats

*编辑感谢skarmats

回答by Francesco Baruchelli

If you don't want to/can't use LINQ you can simply do:

如果您不想/不能使用 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);

回答by Khaled Saleh

Just in case someone wants to use a function instead:

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

    static void Main(string[] args)
    {
        string[] ar = { "apple", "orange", "banana", "pear", "lemon" };

        int half =  ar.Length / 2;

        //  Console.WriteLine(string.Join(',', Split(ar,0, half)));

        Console.WriteLine(string.Join(',', Split(ar,half, ar.Length)));

        Console.ReadKey();
    }


    public static IEnumerable<T> Split<T>(IEnumerable<T> items, int start, int end)
    {
        return items.Skip(start).Take(end);
    }