How do you do it? Given a byte array:
byte[] foo = new byte[4096];
How would I get the first x bytes of the array as a separate array? (Specifically, I need it as an IEnumerable<byte>
)
This is for working with Socket
s. I figure the easiest way would be array slicing, similar to Perls syntax:
@bar = @foo[0..40];
Which would return the first 41 elements into the @bar
array. Is there something in C# that I'm just missing, or is there some other thing I should be doing?
LINQ is an option for me (.NET 3.5), if that helps any.
Array slicing involves taking a subset from an array and allocating a new array with those elements. In Java you can create a new array of the elements in myArray, from startIndex to endIndex (exclusive), like this: Arrays. copyOfRange(myArray, startIndex, endIndex); Java.
Array-slicing is supported in the print and display commands for C, C++, and Fortran. Expression that should evaluate to an array or pointer type. First element to be printed. Defaults to 0.
JavaScript Array slice()The slice() method returns selected elements in an array, as a new array. The slice() method selects from a given start, up to a (not inclusive) given end. The slice() method does not change the original array.
Common examples of array slicing are extracting a substring from a string of characters, the "ell" in "hello", extracting a row or column from a two-dimensional array, or extracting a vector from a matrix. Depending on the programming language, an array slice can be made out of non-consecutive elements.
You could use ArraySegment<T>
. It's very light-weight as it doesn't copy the array:
string[] a = { "one", "two", "three", "four", "five" }; var segment = new ArraySegment<string>( a, 1, 2 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With