Array Clone Bytes 10-40?

Is there any way I can do

var splice = byteArray.Clone(offset, length);
+3
source share
4 answers

You can copy bytes,

byte[] splice = new byte[length];
Array.Copy(byteArray,offset,splice,0,length);
+10
source

If this is a use case for Linq:

var splice = byteArray.Skip(offset).Take(length).ToArray();
+6
source

LINQ binding solution:

var splice = byteArray.Skip(offset)
                      .Take(length)
                      .ToArray();
+3
source

If you find yourself doing this in many places: write an assistant.

public static class ArrayExtensions {
  public static Array ClonePart(this Array input, int offset, int length) {
    if (input == null) throw new ArgumentNullException("input");
    if (offset <= 0 || offset > input.Length) throw new ArgumentOutOfRangeException("offset");
    if (length <= 0 || length > input.Length || length+offset > input.Length)
      throw new ArgumentOutOfRangeException("length");

    var output = Array.CreateInstance(input.GetType().GetElementType(), length);
    Array.Copy(input, offset, output, 0, length);
    return output;
  }
}

(This will work for any type of one-dimensional array.)

+2
source

Source: https://habr.com/ru/post/1754228/


All Articles