我有一个字节数组:
byte[] bytes; // many elements
我需要将其划分为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(); }
这很可爱:
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(); } } }