15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

230 ❘ ChaPTer 10 cOllectiOns<br />

inserting elements<br />

You can insert elements at a specifi ed position with the Insert() method:<br />

racers.Insert(3, new Racer(6, "Phil", "Hill", "USA", 3));<br />

The method InsertRange() offers the capability to insert a number of elements, similarly to the<br />

AddRange() method shown earlier.<br />

If the index set is larger than the number of elements in the collection, an exception of type ArgumentOutOf<br />

RangeException is thrown.<br />

accessing elements<br />

All classes that implement the IList <strong>and</strong> IList < T > interface offer an indexer, so you can access the elements<br />

by using an indexer <strong>and</strong> passing the item number. The fi rst item can be accessed with an index value<br />

0. By specifying racers[3] , you will access the fourth element of the list:<br />

Racer r1 = racers[3];<br />

Getting the number of elements with the Count property, you can do a for loop to iterate through every<br />

item in the collection, <strong>and</strong> use the indexer to access every item:<br />

for (int i = 0; i < racers.Count; i++)<br />

{<br />

Console.WriteLine(racers[i]);<br />

}<br />

Indexed access to collection classes is available with ArrayList , StringCollection ,<br />

<strong>and</strong> List < T > .<br />

Because List < T > implements the interface IEnumerable , you can iterate through the items in the collection<br />

using the foreach statement as well:<br />

foreach (Racer r in racers)<br />

{<br />

Console.WriteLine(r);<br />

}<br />

How the foreach statement is resolved by the compiler to make use of the<br />

IEnumerable <strong>and</strong> IEnumerator interfaces is explained in Chapter 6.<br />

Instead of using the foreach statement, the List < T > class also offers a ForEach() method that is declared<br />

with an Action < T > parameter:<br />

public void ForEach(Action < T > action);<br />

The implementation of ForEach() is shown next. ForEach() iterates through every item of the collection<br />

<strong>and</strong> invokes the method that is passed as parameter for every item.<br />

public class List < T > : IList < T ><br />

{<br />

private T[] items;<br />

//...<br />

public void ForEach(Action < T > action)<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!