Array slicing in C#
C# unlike Perl can directly use the @bar = @foo[0..40];
syntax to slice arrays. However, there are some alternatives to achieve similar functionality.
ArraySegment
For a lightweight option that avoids copying the original array, consider using ArraySegment<T>
. It represents a contiguous portion of an array without copying the underlying elements:
<code class="language-csharp">byte[] foo = new byte[4096]; var segment = new ArraySegment<byte>(foo, 0, 41);</code>
segment
now contains the first 41 bytes of the original foo
array. You can access its contents via the Array
and Offset
attributes, or use it directly in a LINQ expression.
LINQ Skip and Take
If you prefer LINQ, you can use the Skip
and Take
methods to implement slicing:
<code class="language-csharp">IEnumerable<byte> slice = foo.Skip(0).Take(41);</code>
slice
will return the first 41 bytes of the foo
array as a IEnumerable<byte>
sequence.
Customized array slicing function
If neither ArraySegment
nor LINQ meet your needs, you can create a custom array slicing function using index ranges:
<code class="language-csharp">byte[] Slice(byte[] array, int startIndex, int length) { byte[] slice = new byte[length]; Array.Copy(array, startIndex, slice, 0, length); return slice; } byte[] slice = Slice(foo, 0, 41);</code>
The above is the detailed content of How Can I Slice an Array in C#?. For more information, please follow other related articles on the PHP Chinese website!