将数组的一部分复制到列表的快速方法? [英] Fast way to copy part of an array into a List?
问题描述
C#的List<>具有一组CopyTo函数,这些函数将使用快速存储块副本将其内部数组的内容提取到另一个数组中.
C#'s List<> has a set of CopyTo functions that will extract the contents of its internal array into another array using a fast memory block copy.
是否有相反的方法?看起来像...
Is there a way to do this in reverse? It might look like...
var buffer = new List<byte>();
buffer.AddRange(afewbytes);
buffer.AddFromArray(myArray, startIndex, countBytesToCopy);
buffer.AddRange(afewmorebytes);
因为我的列表是列表< byte>各种各样,我宁愿避免一个逐字节复制的循环.
As my List is the List<byte> variety, I'd prefer to avoid a loop that copies byte by byte.
推荐答案
如果集合实现了ICollection<T>
,则List<T>(IEnumerable<T>)
构造函数将使用ICollection<T>.CopyTo
,而byte[]
会使用ICollection<T>.CopyTo
.
The List<T>(IEnumerable<T>)
constructor will use ICollection<T>.CopyTo
if the collection implements ICollection<T>
, which byte[]
will do.
如果只想提取数组的 part ,那将无济于事,但是您可以创建自己的实现ICollection<byte>
的ByteArraySegment
类,并使用ICollection<byte>
实现CopyTo
操作c7>或其他任何东西:
That's not going to help directly if you only want to extract part of the array, but you could create your own ByteArraySegment
class implementing ICollection<byte>
and implement the CopyTo
operation using Buffer.BlockCopy
or whatever:
public class ByteArraySegment : ICollection<byte>
{
private readonly byte[] array;
private readonly int start;
private readonly int count;
public ByteArraySegment(...)
{
// Obvious code
}
public void CopyTo(byte[] target, int index)
{
Buffer.BlockCopy(array, start, target, index, count);
}
// Other ICollection<T> members
}
然后:
List<byte> bytes = new List<byte>(new ByteArraySegment(myArray, start, count));
(或使用具有相同优化功能的AddRange
.)
(Or use AddRange
which has the same optimization.)
这篇关于将数组的一部分复制到列表的快速方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!