How to Use Collections in C#

In this article, I am going to explain how to create the ArrayList and the various methods and properties of the ArrayList.

We know that an array stores a fixed-size sequential collection of elements of the same type. C# also includes collection classes that hold many values or objects in a specific series, that are called ‘collection’.

The collection allows more flexible way work with a group of the object. Unlike arrays, When the needs of application change group of objects you work with can grow and shrink dynamically. For any collections, you can assign a key to any object that you insert into the collection so that you can quickly retrieve the object by using the key.

There are two types of collections available in C#: collections and generic collections. you will learn detail about collections(ArrayList) in this section.

In c# each one collection class to implements the IEnumerable interface so values from the collection can be accessed using a foreach loop.

The System.Collections namespace includes following collections.

It gives a Push() method to add a value in stack and Pop() & Peek() methods are used to retrieve values from the stack. C# includes both, generic and non-generic Stack.

Generic Collections Use
ArrayList It stores objects of any type like an array. on the other hand, ArrayList is no need to define the size like with an array. it grows memory automatically.
SortedList SortedList stores key and value pairs. It automatically arranges elements in ascending order of key by default. C# includes both, generic and non-generic SortedList collection.
Stack Stack stores the values in LIFO style (Last In First Out). It gives a Push() method to add a value in stack and Pop() & Peek() methods to retrieve values from the stack.
Queue Queue stores the values in FIFO style (First In First Out). It manages the order in which the values were added. It is provides two method Enqueue() and Dequeue() method. Enqueue method is used to adds an object to the end of the Queue and dequeue method is used to retrieve values from the collection.
Hashtable Hashtable stores key and value pairs. It retrieves the values by comparing the hash value of the keys.
BitArray BitArray manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0).

ArrayList

ArrayList is a collection type in C#. It is store elements of any data types. It is similar to an array in c#, ArrayList automatically grows memory as you add items to it. Unlike an array, you don’t need to specify the size of ArrayList. In this article, I will explain how to create ArrayList and various methods and properties of the ArrayList.

Initialize ArrayList

ArrayList myArrayList=new ArrayList();

Properties and method of ArrayList

Property Description
Capacity Property is used to gets or sets the number of elements that the ArrayList can contain.
Count Gets the total number of elements actually contained in the ArrayList.
IsFixedSize  IsFixedSize is used to gets a value indicating whether the ArrayList has a fixed size.
IsReadOnly IsReadOnly is used to gets a value indicating whether the ArrayList is read-only.
Item Item property is used to gets or sets the element at the specified index.

Returns true if exists otherwise false.

Method Description
Add()/AddRange() Add() method adds an  object  to the end of  ArrayList.
AddRange() method adds the elements of an ICollection to the end of the ArrayList.
Insert()/InsertRange() Insert() method insert a single elements at the specified index in ArrayList.
InsertRange() method insert all the elements of the specified collection starting from a specified index in ArrayList.
Remove() The Remove() method is used to removes the specified element from the ArrayList.
RemoveRange() The RemoveRange() method is used to removes a scope of an element from ArrayList.
RemoveAt() ArrayList removeAt() method remove the specified index of an element from ArrayList.
Sort() Sorts entire elements of the ArrayList.
Reverse() Reverses method is used to reverses the order of the elements in the entire ArrayList.
Contains  It is used to checks whether the specified element exists in the ArrayList or not.
Clear Removes all the elements in ArrayList.
CopyTo Copies all the elements or range of elements to compatible Array.
GetRange Returns specified number of elements from specified index from ArrayList.
IndexOf Search specified element and returns zero-based index if found. Returns -1 if element not found.
ToArray Returns compatible array from an ArrayList.

Add Element to ArrayList

ArrayList provides two method Add()method to add a single element or the AddRange() method to add multiple elements from the other collections into an ArrayList. Here, the element means the literal value of a primitive or non-primitive type.

Syntax

Add() signature: int Add(Object value)

AddRange() signature:void AddRange(ICollection c)

Example

namespace ArrayListdemo
{
 class Program
 {
 static void Main(string[] args)
 {
 ArrayList arrlist = new ArrayList();
 arrlist.Add(1);
 arrlist.Add(2);
 arrlist.Add("Three");
 arrlist.Add(5.5);
 arrlist.Add(6);
 arrlist.Add('k');

ArrayList arrlist1 = new ArrayList();
 arrlist1.Add(101);
 arrlist1.Add(102);
 arrlist.AddRange(arrlist);

for (int i = 0; i < arrlist.Count; i++)
{
Console.WriteLine(arrlist[i]);
} Console.ReadLine();
}
}
}

you can also add items in ArrayList when you initialize ArrayList using object initializer syntax. you can see below.

ArrayList arrlist = new ArrayList() { 1, "two", 3.3 };

Access Element from ArrayList

We can access an element from ArrayList using the index. in the same way as an array.

namespace ArrayListdemo
{
class Program
{
static void Main(string[] args)
{
ArrayList arrlist = new ArrayList();
arrlist.Add(1);
arrlist.Add(2);
arrlist.Add("Three");
arrlist.Add(5.5);
arrlist.Add(6);
arrlist.Add('k');

int integervalue =Convert.ToInt32(arrlist[0]);

string stringvalue = Convert.ToString(arrlist[2]);

double doublevalue = Convert.ToDouble(arrlist[3]);

char charvalue = Convert.ToChar(arrlist[5]);

var item = arrlist[1];

Console.WriteLine("Integer value :" + integervalue + "\t string value :" + stringvalue + "\t double value :" + doublevalue + "\t char value :" + charvalue + "\t item :" + item );

Console.ReadLine();

}
}
}

Output

Insert Element in ArrayList

We use Insert() method to add a single item at the specified index.

namespace ArrayListdemo
{
class Program
{
static void Main(string[] args)
{
ArrayList arrlist = new ArrayList();
arrlist.Add(1);
arrlist.Add(2);
arrlist.Insert(1, "second value");
foreach (var item in arrlist)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
}

Output

In ArrayList, we can also insert all the values from another collection into ArrayList at the specified index using InsertRange() method.

Example

namespace ArrayListdemo
{
class Program
{
static void Main(string[] args)
{
ArrayList arrlist = new ArrayList();
arrlist.Add(1);
arrlist.Add(2);

ArrayList arrlist1 = new ArrayList();
arrlist1.Add("One");
arrlist1.Add("Two");

arrlist.InsertRange(1, arrlist1);

foreach (var item in arrlist)
{
Console.WriteLine(item);
}

Console.ReadLine();
}
}
}

Output

Remove elements from an ArrayList

In ArrayList Remove() method to remove a specified element from an ArrayList.

ArrayList arrlist = new ArrayList();
arrlist.Add(1);
arrlist.Add(2);
arrlist.Add("One");
arrlist.Add("Two");

arrlist.Remove("One");

foreach (var item in arrlist)
{
Console.WriteLine(item);
}

Console.ReadLine();

Output

In ArrayList, we can also remove an element from the specified index location using the RemoveAt() method.

ArrayList arrlist = new ArrayList();
arrlist.Add(1);
arrlist.Add(2);
arrlist.Add("One");
arrlist.Add("Two");

arrlist.RemoveAt(1);

foreach (var item in arrlist)
{
Console.WriteLine(item);
}

Console.ReadLine();

Output

In ArrayList use the RemoveRange() method to remove multiple elements from the specified index till the specified number of elements in the ArrayList.

ArrayList arrlist = new ArrayList();
arrlist.Add(1);
arrlist.Add(2);
arrlist.Add("One");
arrlist.Add("Two");
arrlist.Add(3);

arrlist.RemoveRange(1,3);

foreach (var item in arrlist)
{
Console.WriteLine(item);
}

Console.ReadLine();

Output

Check existing elements in ArrayList

ArrayList Contains() method checks in case a specified element exists in the ArrayList or not exists. if the element exists in ArrayList returns true otherwise returns false.

ArrayList arrlist = new ArrayList();
arrlist.Add(1);
arrlist.Add(2);
arrlist.Add("One");
arrlist.Add("Two");
arrlist.Add(3);

Console.WriteLine(arrlist.Contains(1));

Console.ReadLine();

Output

Sort and reverse ArrayList

ArrayList includes two method Sort() and Reverse(). Sort() method is used to arranges elements in ascending order. on the other hand, In ArrayList, all element should have the same data type so that it can compare with default comparer or else it will throw a runtime exception.

Reverse() method is used to arranges elements in reverse order. Last element at zero index and so on.

namespace ArrayListdemo
{
class Program
{
static void Main(string[] args)
{
ArrayList arrlist = new ArrayList();
arrlist.Add(1);
arrlist.Add(2);
arrlist.Add(34);
arrlist.Add(15);
arrlist.Add(35);

Console.WriteLine("Original order");

foreach (var item in arrlist)
{
Console.WriteLine(item);
}

Console.WriteLine("Ascending order");
arrlist.Sort();
foreach (var item in arrlist)
{
Console.WriteLine(item);
}

Console.WriteLine("Reverse order");
arrlist.Reverse();
foreach (var item in arrlist)
{
Console.WriteLine(item);
}

Console.ReadLine();

}
}
}

Output

This article introduced you to some basic concepts of how to use ArrayList. I hope, you enjoyed reading this article. Your valuable feedback, questions or comments about this article are always welcome.

 

Leave a Comment