SoFunction
Updated on 2025-03-07

Example analysis of the usage of array segments in C#

This article describes the usage of array segments in C#. Share it for your reference. The specific analysis is as follows:

1. Array segment description

① Structure ArraySegment<T> represents a segment of an array. If a method should return a part of the array, or give

A method passes part of an array and can use array segments. Three parameters can be passed through ArraySegment<T>

(array, the starting position of the array segment, the number of elements selected from the starting position), you can also pass only one parameter

② The array segment will not copy the elements of the original array, but the original array can be accessed through the Array attribute in ArraySegment<T>.

If the elements in the array segment change, these changes will be reflected in the original array

2. An example

private int SumOfSegments(ArraySegment&lt;int&gt;[] segments)
{
  int sum = 0;
  foreach(ArraySegment&lt;int&gt; segment in segments)
  //Loop to store arrays of array segments  {
 for (int i = ; i &lt;  +
  ; i++)
 // Process the array segment, Offset is the starting position in the element array //Count is the number of extracted //Arary is the original array {
   sum += [i];
   // Calculate the sum of elements }
  }
  return sum;
}

Called:

private void button1_Click(object sender, EventArgs e)
{
  int[] arr1 = new int[] { 1,4,5,11,14,18};
  int[] arr2 = new int[] {3,4,5,18,21,27,33 };
  //Define an array of array segments  var segments = new ArraySegment&lt;int&gt;[2]
  {
 new ArraySegment&lt;int&gt;(arr1,0,3),
 new ArraySegment&lt;int&gt;(arr2,3,3)
  };
  var sum=SumOfSegments(segments);
  (());
}

I hope this article will be helpful to everyone's C# programming.