C# ArraySegment

Slicing a string array using Array Segment in C#

C# ArraySegment structure can be used to get a segment of an array. The ArraySegment takes a range of items.

The structure has two forms of constructors.

  1. ArraySegment<T>(T[]): Creates ArraySegment instance from an entire array.
  2. ArraySegment<T>(T[], Int32, Int32): Creates ArraySegment with a range. First parameter is an array. The second parameter is OffSet, the zero-based index of the first element in the range. The third parameter is the Count, the number of elements in the range.

The following code snippet uses both constructors to create two ArraySegment instances.

int[] numArray = { 1, 3, 5, 7, 9, 11, 9, 7, 5, 3, 1, 1 };
// Create an ArraySegment that wraps the entire array
ArraySegment<int> arrSeg = new ArraySegment<int>(numArray);
// Create an ArraySegment with specified start index and count
ArraySegment<int> num5 = new ArraySegment<int>(numArray, 2, 5);

In the above code, the first ArraySegment wraps the entire array, and the second ArraySegment copies an array of items from the 2nd position to the next 5 items.

The following code snippet reads all the items of an ArraySegment.

// Read ArraySegment items
for (int i = num5.Offset; i < num5.Offset + num5.Count; i++)
{
    Console.WriteLine($"{num5.Array[i]}");
}

ArraySegment Properties

The following table describes ArraySegment properties.

  1. Array: Original array containing the range of elements that the array segment delimits.
  2. Count: The number of elements in the range delimited by the array segment.
  3. Offset: The position of the first element in the range delimited by the array segment relative to the start of the original array.

Slicing ArraySegment

The Slice() method of the ArraySegment slices an ArraySegment. The Slice method can return a number of items or a range of the segment. The first parameter is the starting index, followed by the number of items.

The following code snippet creates a slice of an ArraySegment using the Slice method and reads the items in the segment.

// String array
string[] authors = { "Mahesh", "Allen", "Neel", "David", "Monica", "Naveen" };
// Array segment
ArraySegment<string> topAuthors = new ArraySegment<string>(authors, 0, 5);
ArraySegment<string> slice = topAuthors.Slice(2, 3);
for (int i = slice.Offset; i < slice.Offset + slice.Count; i++)
{
    Console.WriteLine($"{slice.Array[i]}");
}

Learn more about Arrays here: Working with C# Arrays.


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.