Home > Backend Development > C++ > How Can I Slice an Array in C#?

How Can I Slice an Array in C#?

Linda Hamilton
Release: 2025-01-14 20:15:48
Original
420 people have browsed it

How Can I Slice an Array in C#?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template