将数组划分为子序列数组

nik*_*nik 11 c#

我有一个字节数组:

byte[] bytes;  // many elements
Run Code Online (Sandbox Code Playgroud)

我需要将它划分为X元素的字节数组的子序列.例如,x = 4.

如果bytes.Length不通过X乘,再加入0至最后子阵列使所有subsequnce的长度必须是X.

Linq可用.

PS:我的尝试

static void Main(string[] args)
{
    List<byte> bytes = new List<byte>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

    int c = bytes.Count / 4;

    for (int i = 0; i <= c; i+=4)
    {
        int diff = bytes.Count - 4;

        if (diff < 0)
        {

        }
        else
        {
            List<byte> b = bytes.GetRange(i, 4);
        }
    }

    Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 30

这很可爱:

static class ChunkExtension
{
    public static IEnumerable<T[]> Chunkify<T>(
        this IEnumerable<T> source, int size)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (size < 1) throw new ArgumentOutOfRangeException("size");
        using (var iter = source.GetEnumerator())
        {
            while (iter.MoveNext())
            {
                var chunk = new T[size];
                chunk[0] = iter.Current;
                for (int i = 1; i < size && iter.MoveNext(); i++)
                {
                    chunk[i] = iter.Current;
                }
                yield return chunk;
            }
        }
    }
}
static class Program
{
    static void Main(string[] args)
    {
        List<byte> bytes = new List<byte>() {
              1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
        var chunks = bytes.Chunkify(4);
        foreach (byte[] chunk in chunks)
        {
            foreach (byte b in chunk) Console.Write(b.ToString("x2") + " ");
            Console.WriteLine();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 简单修复:在循环外声明"int i",如果"i"小于"size",则使用Array.Resize(...). (2认同)

小智 6

如果你总是得到source.Length % size != 0,那么投票的答案是有效的,尽管它太冗长了.这里有一个更好的实现:

public static IEnumerable<T[]> AsChunks<T>(IEnumerable<T> source, int size)
{
    var chunk = new T[size];
    var i = 0;
    foreach(var e in source)
    {
        chunk[i++] = e;
        if (i==size)
        {
            yield return chunk;
            i=0;
        }
    }
    if (i>0) // Anything left?
    {
        Array.Resize(ref chunk, i);
        yield return chunk;
    }
}

void Main()
{
    foreach(var chunk in AsChunks("Hello World!",5))
        Console.WriteLine(new string(chunk));
}
Run Code Online (Sandbox Code Playgroud)

生产:

  1. 你好
  2. WORL
  3. d!