ArrayList - Collections in C#

What is a Collection?

Similar to arrays, collections are structures that store a large number of data, or more precisely, objects. What is stored in collections is also an object. Arrays are defined by specifying a data type, as with variables. Collections, on the other hand, store all kinds of data of type object.

We can explain the differences between collections and arrays as follows:

  • Arrays store one type of data. They cannot store data other than the type specified when defining it (see Arrays ). Collections, on the other hand, can store different types of data. That is, while the 1st element is a string, the other can be a number, the other a boolean, etc.
  • The number of elements of arrays is determined initially and cannot be changed afterwards. Collections, on the other hand, have a dynamic structure. Elements can be added or removed with the Add and Remove methods. You can even add elements in between.

The above-mentioned collections can also be considered as advantages over arrays.

Should I use an array or a collection in my program? How should I decide this?

The disadvantage of collections over arrays is this: We said that every element in the collection is stored as object. While adding or retrieving value type data such as int, bool, double, conversion will be required, as the size of the collection increases, the number of conversions will increase and the performance of our application will decrease.

Therefore, when answering the question of which one should we use, we should calculate well what we need. If the data we are going to store will all be of the same type and we do not need to increase or decrease the number of elements, we should definitely prefer arrays.

There are various types of collections in programming. The most general purpose of these is the ArrayList class.

Using ArrayList

First the System.Collections class needs to be included in our project:

using System.Collections;

The initial capacity of a collection object produced from the ArrayList class is 4. We mentioned earlier that capacity is dynamic. As soon as the capacity is full, it is doubled automatically. In other words, when the 5th element is added to the collection, the capacity is increased to 8. Similarly, when adding the 9th element, the capacity is increased to 16. When adding the 17th element, it is increased to 32, and so on.

Generating the collection object is as follows:

my ArrayList list = new ArrayList();

Thanks to the above command line, we will have a collection object named MyList from ArrayList class.

The Add method is used to add data to the collection . In whatever order we add, the index number of the elements will be in that order. Index numbers always start from 0.

mylist.Add("monitor");

mylist.Add(458);

mylist.Add(true);

Elements added as above can be different or of the same type.

The element added with the Add method will be added to the end of the collection. If we want to add to a certain index number, we can use the Insert method.

my ArrayList list = new ArrayList();
mylist.Add("monitor");
mylist.Add("harddisk");
mylist.Add("cpu");
mylist.Add("keyboard");
mylist.Add("safe");
mylist.Insert(2, "mouse");

In the example above, the Insert method is used in the last row. Insert method takes 2 parameters. The first is the index number of the element to be added, and the second is the value to be added.

In the example, the data "mouse" is assigned to item 2 of the collection. In this case, element 2 and the ones after it are shifted forward by 1.

The InsertRange method, on the other hand, is used to add the elements of another collection sequentially to the desired place of the collection. In the example below, the elements of the collection named list2 are inserted into the list collection starting from element number 2.

list.InsertRange(2, list2);

The Remove method is used to delete a value from the collection. The value of the element to be deleted is given as a parameter to the Remove method. If there is more than one element with the given value, only the first one found, that is, the one with the smaller index number, is deleted. 

mylist.Add("monitor");
mylist.Add("harddisk");
mylist.Add("cpu");
mylist.Remove("harddisk");

In the example above, the element with the hard disk value has been deleted. The index numbers of the elements that come after the deleted element will shift back by 1.

When deleting with Remove, the number of elements of the collection will decrease, but its capacity will not change. 

If we want to delete according to the index number of the element, we can use the RemoveAt method. The RemoveAt method takes the index number of the element to be deleted as a parameter. For example, to delete element 5:

mylist.RemoveAt(5);

We use the RemoveRange method to delete a large number of elements from a certain index number. This method takes two parameters. The first is the index number of the element to be deleted, and the second is how many elements will be deleted.

mylist.RemoveRange(4,3);

With the above line, 3 elements have been deleted from the fourth element of the collection, that is, the fifth element.

If we want to delete all the elements of a collection at once, we can use the Clear method.

mylist.Clear();

We can use foreach or for loop to handle all the elements in the collection. The thing to note here is that there may be an error when converting objects of type object to the desired type.

If we want to print all the elements of a collection into label1 one after the other:

foreach (string a in list)
       label1.Text += a + "\n";

We can do the same with a for loop:

for(int i=0; i<list.Count;i++)
        label1.Text += list[i] + "\n";

The number of elements of the collection is obtained with the Count property used here. The element number i of the collection is reached in the form of list[i] in the loop. Since index numbers start from 0, it is ensured that the loop ends 1 before the element number.

The Capacity property is used to find out the capacity of the collection .

label1.Text = list.Capacity.ToString();

AddRange method is used to add all the elements of one collection to another collection. In the example below, all the elements of the collection named list2 are appended to the end of list1.

list1.AddRange(list2);

With the Contains method, we can detect whether a value is present in the collection. In the example below, the result will return true if there is an element with a value of "Ahmed" in the collection named list, otherwise false.

if ( list.Contains("John") )
       label1.Text = "Search Phrase Found.";
else
       label1.Text = "Not found.";

If a data searched with the IndexOf method is found in the collection, the index number of that element can be obtained.

int indexNo = list.IndexOf("Ali");

LastIndexOf method also works like IndexOf. However, if the searched data occurs more than once, it returns the index number of the last one.

int indexNo = list.LastIndexOf("Ali");

With the CopyTo method, we can copy the elements of the collection into an array of compatible type. It will throw an error if the types of the elements to be transferred are not the same as the target array. In addition, the length of the target directory should be sufficient for this process. In the example below, a string type array with 12 elements was created and all the elements of the collection named list were copied to this array in the same order.

string[ ] array1 = new string[12];
list.CopyTo(array1);

The CopyTo method can be used in several ways (overloaded method). By using list.CopyTo( array1, 2), it is possible to copy the elements in the collection starting from the 2nd element of the array. 

It can also be used to take 4 parameters like this:

list.CopyTo( collectionIndexNo, arrayName, arrayIndexNo, Number of Elements to be copied);

With such a use, it is possible to copy the desired number of elements to the desired location of the array, starting from the specified numbered element of the collection.

list.CopyTo(3,array1,2,4);

A part of a collection can be assigned to another collection with the GetRange method. In the example below, the first 4 elements of the list1 collection are assigned to the list2 collection.

ArrayList list1 = new ArrayList();
list1.Add("Manisa");
list1.Add("Ankara");
list1.Add("Izmir");
list1.Add("Cankiri");
list1.Add("Mugla");
list1.Add("Hatay");
 
ArrayList list2 = new ArrayList();
 
list2 = list1.GetRange(0, 4);

With the reverse method, the order of the elements of a collection can be changed, in other words, they can be reversed.

list.Reverse();

By using the reverse method to take two parameters, only a certain part of the collection can be reversed.

list.Reverse( 4, 5 );

With the above line of code, a total of 5 elements, starting from the 4th element of the list collection, will be sorted in reverse.

With the Sort method, all elements of the collection can be sorted in ascending order. 

list.Sort();

 

c# using collections, what is collection, difference between collection and array, differences between collections and arrays, using arraylist, advantages of using arraylist, how to use arraylist, using collections and arraylist

EXERCISES

There are no examples related to this subject.



COMMENTS




Read 695 times.

Online Users: 449



arraylist-collections-c-sharp