C# ArraySegment

Learn how to use ArraySegment structure in C# to get a portion of an array.

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 Count, the number of elements in the range.

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

  1. int[] numArray = { 1, 3, 5, 7, 9, 11, 9, 7, 5, 3, 1, 1 };   
  2.   
  3. // Create an ArraySegment wraps entire array 
  4. ArraySegment<int> arrSeg = new ArraySegment<int>(numArray);   
  5.   
  6. // Array segment  
  7. ArraySegment<int> num5 = new ArraySegment<int>(numArray, 2, 5);

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

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

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

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.

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

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