15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

140 ❘ ChaPTer 6 ArrAys And tuples<br />

arraysegment < T ><br />

The struct ArraySegment < T > represents a segment of an array. If parts of an array should be returned<br />

from or passed to a method, a segment can be used. Instead of passing the array, offset, <strong>and</strong> count with<br />

separate parameters to a method, you can pass a single parameter with ArraySegment < T > . With this<br />

structure the information about the segment (the offset <strong>and</strong> count) is contained within the members of<br />

the structure.<br />

The method SumOfSegments takes an array of ArraySegment < int > elements to calculate the sum of all the<br />

integers that are defi ned with the segments <strong>and</strong> returns the sum:<br />

static int SumOfSegments(ArraySegment < int > [] segments)<br />

{<br />

int sum = 0;<br />

foreach (var segment in segments)<br />

{<br />

for (int i = segment.Offset; i < segment.Offset +<br />

segment.Count; i++)<br />

{<br />

sum += segment.Array[i];<br />

}<br />

}<br />

return sum;<br />

}<br />

code snippet ArraySegmentSample/Program.cs<br />

This method is used by passing an array of segments. The fi rst array element references three elements of<br />

ar1 starting with the fi rst element; the second array element references three elements of ar2 starting with<br />

the fourth element:<br />

int[] ar1 = { 1, 4, 5, 11, 13, 18 };<br />

int[] ar2 = { 3, 4, 5, 18, 21, 27, 33 };<br />

var segments = new ArraySegment < int > [2]<br />

{<br />

new ArraySegment < int > (ar1, 0, 3),<br />

new ArraySegment < int > (ar2, 3, 3)<br />

};<br />

var sum = SumOfSegments(segments);<br />

It ’ s important to note that array segments don ’ t copy the elements of the originating<br />

array. Instead, the originating array can be accessed through ArraySegment < T > . If<br />

elements of the array segment are changed, the changes can be seen in the original<br />

array.<br />

enumeraTions<br />

By using the foreach statement you can iterate elements of a collection (see Chapter 10) without<br />

the need to know the number of elements inside the collection. The foreach statement uses an<br />

enumerator. Figure 6 - 7 shows the relationship between the client invoking the foreach method <strong>and</strong><br />

the collection. The array or collection implements the IEnumerable interface with the<br />

GetEnumerator() method. The GetEnumerator() method returns an enumerator implementing<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!