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<int>[] segments) { int sum = 0; foreach(ArraySegment<int> segment in segments) //Loop to store arrays of array segments { for (int i = ; i < + ; 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<int>[2] { new ArraySegment<int>(arr1,0,3), new ArraySegment<int>(arr2,3,3) }; var sum=SumOfSegments(segments); (()); }
I hope this article will be helpful to everyone's C# programming.