如何将数组拆分为n个部分? [英] How can I split an array into n parts?

查看:70
本文介绍了如何将数组拆分为n个部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字节列表,我想将此列表分成较小的部分.

I have a list of bytes and I want to split this list into smaller parts.

var array = new List<byte> {10, 20, 30, 40, 50, 60};

此列表有6个单元格.例如,我想将其分为3个部分,每个2个字节.

This list has 6 cells. For example, I want to split it into 3 parts containing each 2 bytes.

我试图编写一些for循环,并使用2D数组实现我的目的,但我不知道这是一种正确的方法.

I have tried to write some for loops and used 2D arrays to achieve my purpose but I don't know it is a correct approach.

            byte[,] array2D = new byte[window, lst.Count / window];
            var current = 0;
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < cols; j++)
                {
                    array2D[i, j] = lst[current++];
                }
            }

推荐答案

一种不错的方法是创建一个通用/扩展方法来拆分任何数组.这是我的:

A nice way would be to create a generic/extension method to split any array. This is mine:

/// <summary>
/// Splits an array into several smaller arrays.
/// </summary>
/// <typeparam name="T">The type of the array.</typeparam>
/// <param name="array">The array to split.</param>
/// <param name="size">The size of the smaller arrays.</param>
/// <returns>An array containing smaller arrays.</returns>
public static IEnumerable<IEnumerable<T>> Split<T>(this T[] array, int size)
{
    for (var i = 0; i < (float)array.Length / size; i++)
    {
        yield return array.Skip(i * size).Take(size);
    }
}

此外,该解决方案被推迟.然后,只需在数组上调用split(size).

Moreover, this solution is deferred. Then, simply call split(size) on your array.

var array = new byte[] {10, 20, 30, 40, 50};
var splitArray = array.Split(2);

根据要求,这是一种通用/扩展方法,用于从数组中获取方形2D数组:

As requested, here is a generic/extension method to get a square 2D arrays from an array:

public static T[,] ToSquare2D<T>(this T[] array, int size)
{
    var buffer = new T[(int)Math.Ceiling((double)array.Length/size), size];
    for (var i = 0; i < (float)array.Length / size; i++)
    {
        for (var j = 0; j < size; j++)
        {
            buffer[i, j] = array[i + j];
        }
    }
    return buffer;
}

玩得开心:)

这篇关于如何将数组拆分为n个部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆