INTRODUCTION Sometimes is necessary to hold more than one object in your program as an object, a part, of a bigger collection. For example, one might want to store information about each book in his possession. So, a collection which represents these books must be defined. The C# language and the .Net environment offer you numerous techniques for implementing these kinds of collections in your code. One of those techniques is by using a collection structure.
COLLECTIONS The main purpose of a collection is to supply a way of iterating through objects in a larger structure and perform some actions with them. This is accomplished with the foreach loop, the only advantage a collection offers. This can be accomplished only if the collection object can supply an enumerator reference in order for the iteration to take place. For example suppose the variable books is a collection. We can iterate through each object in the collection by using this template: foreach (string myString in books) { DoSomething(); } The collections books contains some string objects. We iterate through each one of those objects and do something, for example add the string to a database considering that the string variable is the title of each book. USING COLLECTIONS When iterating through collections, you cannot predict the order that the objects will appear. If you want to retrieve the objects in a determined order you can use an array by supplying an index. Besides, you are not allowed to add or remove objects to a collection, you can only access them. The foreach command also works with arrays; arrays are considered to be collections. In this case the enumerator iterates the objects in an orderly way from 0 till end. Finally, in arrays we can add and remove objects. To actually use a collection you must implement the IEnumerable interface in it. This interface defines only one method named GetEnumerator(). If you want your custom structs or classes to implement this interface you have to write quite some code that is beyond the scope of this tutorial. As an example, we will define a collection of strings and we will iterate through them. For this example you also need to add the Using System.Collections statement: static void Main(string[] args) { ArrayList myArray = new ArrayList(); myArray.Add(1); myArray.Add(2); myArray.Add(3); myArray.Add(4); myArray.Add(5); foreach (int i in myArray) { Console.WriteLine(i.ToString()); } Console.ReadLine(); } A collection is defined as an array list. We then insert some integer values in it. We could also insert any other object available such as a string, a custom-made class etc… Next, we iterate through each integer object in our collection and write its value to the screen. Since it is an array the iteration is ordered. Try your own code and see what happens.
Trackback(0)
 |