The List<T>(IEnumerable<T>)
constructor will use ICollection<T>.CopyTo
if the collection implements ICollection<T>
, which byte[]
will do.
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
}
Then:
List<byte> bytes = new List<byte>(new ByteArraySegment(myArray, start, count));
(Or use AddRange
which has the same optimization.)