本文介绍了分数组子阵列的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字节数组:
字节[]字节; //许多元素
我需要把它分成x的元素的字节数组的序列。例如x = 4
如果bytes.Length没有用X乘,然后加上0至最后子阵列等等所有subsequnce长度必须是X
的LINQ提供。
PS:我尝试
静态无效的主要(字串[] args)
{
清单<位>字节=新列表与所述;字节>(){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差异= bytes.Count - 4; 如果(差异℃下)
{ }
其他
{
清单<位> B = bytes.GetRange(ⅰ,4);
}
}
Console.ReadKey();
}
解决方案
这是很可爱的:
静态类ChunkExtension
{
公共静态的IEnumerable< T []> Chunkify< T>(
这IEnumerable的< T>源,INT大小)
{
如果(来源== NULL)抛出新的ArgumentNullException(源);
如果(大小和。1)抛出新ArgumentOutOfRangeException(大小);
使用(VAR ITER = source.GetEnumerator())
{
而(iter.MoveNext())
{
VAR块=新的T [大小]
块[0] = iter.Current;
的for(int i = 1; I<大小和放大器;&安培; iter.MoveNext();我++)
{
块[I] = iter.Current;
}
产生回报块;
}
}
}
}
静态类节目
{
静态无效的主要(字串[] args)
{
清单<位>字节=新的List<位>(){
1,2,3,4,5,6,7,8,9,10,11};
变种块= bytes.Chunkify(4);
的foreach(以字节块[]块)
{
的foreach(在组块字节二)Console.Write(b.ToString(×2)+);
Console.WriteLine();
}
}
}
I have a byte array:
byte[] bytes; // many elements
I need to divide it into subsequence of byte arrays of X elements. For example, x = 4.
If bytes.Length does not multiply by X, then add 0 to last subsequence array so Length of all subsequnce must be X.
Linq available.
PS: my attempts
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();
}
解决方案
This is quite cute:
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();
}
}
}
这篇关于分数组子阵列的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!