Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array slices in C#

Tags:

arrays

c#

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 Sockets. 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.

like image 443
Matthew Scharley Avatar asked Jan 02 '09 10:01

Matthew Scharley


People also ask

What is array slicing in C?

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.

Can we slice array in C?

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.

What is an array slice?

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.

What is array slice explain with example?

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.


1 Answers

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 ); 
like image 146
Mike Scott Avatar answered Oct 21 '22 12:10

Mike Scott