简体   繁体   English

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

[英]Splitting an array into 2 arrays C#

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.我知道如何使用 for 循环来做到这一点,但我想知道是否有更快/更好的方法来做到这一点。 I also need to be able to correctly split an array even if it has an odd number of items, eg:我还需要能够正确拆分数组,即使它有奇数个项目,例如:

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'

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 / 2 elements, and the second one skips the first array.Length / 2 elements, it means there isn't any conflict between these two arrays. firstArray 取array.Length / 2元素,第二个跳过第一个array.Length / 2元素,这意味着这两个数组之间没有任何冲突。 Of course if the number of elements is odd we cannot split the array into two equal size parts.当然,如果元素数量是奇数,我们不能将数组分成两个相等大小的部分。

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();
string[] words = {"apple", "orange", "banana", "pear", "lemon"};
int mid = words.Length/2;
string[] first = words.Take(mid).ToArray();
string[] second = words.Skip(mid).ToArray();

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

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

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

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

You can achive that quite easily using range notation:您可以使用范围表示法很容易地实现这一点:

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..];

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM