Collections
In many applications we need to create and manage groups of related objects. There are two ways to do it, either by creating an array of objects or by creating a collection of objects.
Arrays are most useful for creating a fixed number of strongly typed objects.
Collections provide a more flexible way to work with groups of objects and the group of objects you work with can grow and shrink dynamically as the needs of the application changes. It also allows access to a list of items using an index. C# collections classes are defined as part of the System.Collections. So first we need to use the System.Collections namespace.
Various Collections Classes and Their Usage
The following are the various commonly used classes of the System.Collections namespace.
ArrayList
ArrayList represents an ordered collection of a specified object that can be indexed individually. It allows dynamic memory allocation, adding, searching and sorting items in the list.
The following are the properties of the ArrayList class:
- Capacity: Gets or sets the number of elements that the ArrayList can contain.
- Count: Returns the number of elements present in the ArrayList.
- IsFixedSize: Returns a value indicating whether the ArrayList has a fixed size.
- IsReadOnly: Returns a value indicating whether the ArrayList is read-only.
- Item: Gets or sets the element at the specified index position.
The following are the methods of the ArrayList class:
- public virtual int add(object value); Inserts the object at the end of the ArrayList.
- public virtual void AddRange(Icollection c); Adds the elements of a collection to the end of the ArrayList.
- public virtual void Clear(); Removes all the elements from the ArrayList. Does not affect the capacity of the ArrayList.
- public virtual bool Contains(object item); Determines whether an element is present or not in the ArrayList.
- public virtual ArrayList GetRange( int index, int count ); Returns an ArrayList that represents a subset of the elements in the source ArrayList.
- public virtual int IndexOf(object); Returns the index of the first occurrence of a value in the ArrayList or in a portion of it.
- public virtual void Insert(int index, object value); Inserts an element into the ArrayList at the specified index.
- public virtual void InsertRange(int index, ICollection c); Inserts the element of a collection into the ArrayList at the specified index.
- Public virtual void Remove(object obj); Removes the first occurrence of a specified object from the ArrayList.
- public virtual void RemoveAt(int index); Removes the element at the given specified index of the ArrayList.
- public virtual void RemoveRange(int index,int count); Removes a range of elements from the ArrayList.
- public virtual void Reverse(); Reverses the order of the elements in the ArrayList.
- public virtual void Sort(); Sorts all the elements in the ArrayList.
- public virtual void TrimToSize(); Sets the capacity to the actual number of elements present in the ArrayList. Basically the capacity is not increased one by one. Capacity is just doubled each time whenever the size reaches the threshold. So the TrimToSize() method sets the capacity to the exact the size of the ArrayList.
The following is the example:
- using System;
- using System.Collections;
-
- namespace Collection_Example
- {
- class Program
- {
- static void Main(string[] args)
- {
- ArrayList al = new ArrayList();
- ArrayList al1 = new ArrayList();
-
- al1.Add('a');
- al1.Add('b');
- al.Add('k');
- al.Add('l');
- al.Add('j');
-
- al.InsertRange(2,al1);
-
-
- Console.WriteLine("Count: {0}", al.Count);
- Console.WriteLine("Capacity before TrimToSize: {0} ", al.Capacity);
- al.TrimToSize();
- Console.WriteLine("Capacity after TrimToSize: {0} ", al.Capacity);
- Console.WriteLine(al.Contains('b'));
- Console.Write("Element befor sort: ");
- foreach (object obj in al)
- Console.Write(obj + " ");
- Console.Write("\nElement after sort: ");
- al.Sort();
- foreach (object obj in al)
- Console.Write(obj + " ");
- al.Reverse();
- Console.Write("\nElement after reverse: ");
- foreach (object obj in al)
- Console.Write(obj + " ");
- Console.WriteLine("\nIndex of char 'k' is : {0}", al.IndexOf('k'));
-
- al.Clear();
- Console.WriteLine("\nCount: {0}", al.Count);
- Console.ReadKey();
- }
- }
- }
OutputHashTable
The Hashtable class represents a collection of key-and-value pairs organized based on the hash code of the key. It uses the key to access the elements in the collection. Hash table is used when you need to access elements using a key. Each item in the hash table has a key/value pair. The key is used to access the items in the collection.
The following are the properties of HashTable class:
- Count: Returns the number of elements present in the Hashtable.
- IsFixedSize: Returns a value indicating whether the Hashtable has a fixed size.
- IsReadOnly: Returns a value indicating whether the Hashtable is read-only.
- Item: Gets or sets the value with the specific key.
- Keys: Returns an ICollection containing the keys in the HashTable.
- Values: Returns an ICollection containing the values in the HashTable.
The following are the methods of the HashTable Class:
- public virtual void add(object key,object value); Adds a value with the specified key into the HashTable.
- public virtual void Clear(); Clears the HashTable.
- public virtual bool ContainsKey(object key); Determines whether the HashTable contains a specific key, if Yes then returns true otherwise it returns false.
- public virtual bool ContainsValue(object key); Determines whether the HashTable contains a specific value, if Yes then returns true otherwise it returns false.
- public virtual void Remove(object key); Removes an element with the specific key from the HashTable.
The following is the example:
- using System;
- using System.Collections;
-
- namespace Collection_Example
- {
- class Program
- {
- static void Main(string[] args)
- {
- Hashtable ht = new Hashtable();
-
- ht.Add(1, "Alwar");
- ht.Add(12, "Ajmer");
- ht.Add(8, "Jaipur");
- ht.Add(4, "Kota");
- Console.WriteLine("Count : {0}", ht.Count);
- if (ht.ContainsValue("Sikar"))
- Console.WriteLine("Sikar is already exist in the HashTable");
- else
- ht.Add(5, "Sikar");
-
-
- Console.WriteLine("Values are :");
- ICollection values = ht.Values;
- foreach (string str in values)
- Console.WriteLine(str);
-
- Console.WriteLine("Keys are :");
- ICollection keys = ht.Keys;
- foreach (int i in keys)
- Console.WriteLine(i);
- ht.Remove(3);
- ht.Clear();
- Console.ReadKey();
- }
- }
- }
OutputSortedList
SortedList represents a collection of key-value pairs sorted by the keys and are accessible by key and by index. A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. Note that SortedList is always sorted by the key value.
The following are the properties of the SortedList class:
- Capacity: Gets or sets the number of elements that the SortedList can contain.
- Count: Returns the number of elements present in the SortedList.
- IsFixedSize: Returns a value indicating whether the SortedList has a fixed size.
- IsReadOnly: Returns a value indicating whether the SortedList is read-only.
- Item: Gets or sets the value associated with a specific key in the SortedList.
- Keys: Returns an ICollection containing the keys in the SortedList.
- Values: Returns an ICollection containing the values in the SortedList.
Method of the SortedList Class:
- public virtual void add(object key , object value); Adds a value with the specified key into the SortedList.
- public virtual void Clear(); Clears the SortedList.
- public virtual bool ContainsKey(object key); Determines whether the SortedList contains a specific key, if Yes then returns true otherwise it returns false.
- public virtual bool ContainsValue(object key); Determines whether the SortedList contains a specific value, if Yes then returns true otherwise it returns false.
- public virtual object GetByIndex(int index); It returns the value at the specified index of the SortedList.
- public virtual object GetKey(int index); Returns the key at the specified index of the SortedList.
- public virtual IList GetKeyList(); Gets the keys in the SortedList.
- public virtual IList GetValueList(); Gets the values in the SortedList.
- public virtual int IndexOfKey(object key); Gets the index of the specified key in the SortedList.
- public virtual int IndexOfValue(object value); Gets the index of the first occurrence of the specified value in the SortedList.
- public virtual void Remove(object key); Remove an element with the specific key from the SortedList.
- public virtual void RemoveAt(int index); Removes the element at the specified index of SortedList.
The following is the example:
- using System;
- using System.Collections;
-
- namespace Collection_Example
- {
- class Program
- {
- static void Main(string[] args)
- {
- SortedList sl = new SortedList();
-
- sl.Add(1, "Alwar");
- sl.Add(12, "Ajmer");
- sl.Add(8, "Jaipur");
- sl.Add(4, "Kota");
- Console.WriteLine("Count : {0}", sl.Count);
- if (sl.ContainsValue("Sikar"))
- Console.WriteLine("Sikar is already exist in the SortedList");
- else
- sl.Add(5, "Sikar");
- Console.WriteLine("Value and key at position 2 is {0} , {1}", sl.GetByIndex(2), sl.GetKey(2));
- Console.Write("keys are : ");
- foreach (int i in sl.Keys)
- Console.Write(i + " ");
- sl.Remove(3);
-
- IList keys = sl.GetKeyList();
- IList values = sl.GetValueList();
- Console.WriteLine("\nValues are :");
- foreach (object obj in values)
- Console.WriteLine(obj);
- Console.WriteLine("Index of Ajmer is : {0}", sl.IndexOfValue("Ajmer"));
-
- sl.RemoveAt(2);
- Console.ReadKey();
- }
- }
- }
Output
Stack
A Stack is a Last In First Out (LIFO) collection of objects. A Stack is used when you need last-in, first-out access to the objects. That means accessing the last inserting item. A Stack basically consists of two operations, Push and Pop. When you insert an element into the stack, it is called pushing the item and when you extract the item from the stack, it is called popping the item. Both Push and Pop are done at the top of the stack. To use the Stack data type in C# first you need to use the System.Collections namespace.
The following are the properties of Stack:
- Count: Returns the number of elements in the stack.
The following are the methods of stack:
- public virtual void Push(object obj); Simply inserts an object at the top of the stack.
- public virtual object Pop(object obj); Simply removes and returns the object from the top of the stack.
- public virtual void Clear(); Clears the stack. Removes all the elements from the stack.
- public virtual object Peek(); Returns the objects from the top of the stack (without removing).
- public virtual object[] ToArray(); Copies the stack into an object array.
- public virtual bool Contains(object obj); Checks whether an element exists in the stack. Returns True when an item exists in the stack otherwise it returns False.
The following is the example:
- using System;
- using System.Collections;
-
- namespace Test_Cdac
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- Stack st = new Stack();
-
- st.Push("Pankaj");
- st.Push(1);
- st.Push(10.5);
- st.Push(true);
- st.Push('A');
-
- Console.WriteLine("Count : {0}", st.Count);
- Console.WriteLine();
-
- Console.WriteLine("Element in stack : ");
- foreach (object obj in st)
- Console.WriteLine(obj);
- Console.WriteLine();
-
- Console.WriteLine("Top most element of stack : {0}", st.Peek());
- Console.WriteLine();
-
- object TopElement = st.Pop();
- Console.WriteLine("Removing Top element of Stack = {0}\nNow Top element of stack = {1}\n", TopElement, st.Peek());
-
- if (st.Contains("Pankaj"))
- Console.WriteLine("Pankaj Found");
- else
- Console.WriteLine("Pankaj Not found");
-
- Object[] ob=st.ToArray();
- Console.WriteLine();
- foreach (object obj in ob)
- Console.WriteLine(obj);
-
- st.Clear();
- Console.WriteLine();
- Console.WriteLine("Count : {0}", st.Count);
- Console.ReadKey();
- }
- }
- }
Output:QueueA Queue is a First-In-First-Out (FIFO) collection of objects. Queue is used when you need first-in, first-out access to objects. That means accessing the first inserting item. A Queue basically consists of two operations Enqueue and Dequeue. When you insert an element into a Queue, it is called Enqueue and when you extract an item from the Queue, it is called Dequeue. The Enqueue operation is done at the end of the queue and the Dequeue operation is done at end of the queue. To use the Queue data type in C# you need to use the System.Collections namespace.
The following is the property of Queue:
- Count: Returns the number of elements in the Queue.
The following are the methods of Queue:
- public virtual void Enqueue(object obj); Simply inserts an object at the end of the queue.
- public virtual object Dequeue(object obj); Simply removes and returns the object from the front of the queue.
- public virtual void Clear(); Clears the queue. This method removes all the elements from the queue.
- public virtual object Peek(); This method returns the object from the front of the queue (without removing).
- public virtual object[] ToArray(); Copies the queue into an object array.
- public virtual bool Contains(object obj); Checks whether an element exists in the queue. Returns True when the item exists in the queue otherwise it returns False.
- public virtual void TrimToSize(); Sets the capacity to the actual number of elements present in the Queue. Basically the capacity is not increased one by one. Capacity is just doubled each time whenever the size reaches the threshold. So the TrimToSize() method sets the capacity to the exact the size of the queue.
The following is the example:
- using System;
- using System.Collections;
-
- namespace Teq_Cdac
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- Queue q = new Queue();
-
- q.Enqueue("Pankaj");
- q.Enqueue(1);
- q.Enqueue(10.5);
- q.Enqueue(true);
- q.Enqueue('A');
-
- Console.WriteLine("Count : {0}", q.Count);
- Console.WriteLine();
-
- Console.WriteLine("Element in Queue : ");
- foreach (object obj in q)
- Console.WriteLine(obj);
- Console.WriteLine();
-
- Console.WriteLine("End element of Queue : {0}", q.Peek());
- Console.WriteLine();
-
- object TopElement = q.Dequeue();
- Console.WriteLine("Removing End element of Queue = {0}\nNow End element of Queue = {1}\n", TopElement, q.Peek());
-
- if (q.Contains("Pankaj"))
- Console.WriteLine("Pankaj Found");
- else
- Console.WriteLine("Pankaj Not found");
-
- Object[] ob=q.ToArray();
- Console.WriteLine();
- foreach (object obj in ob)
- Console.WriteLine(obj);
-
- q.TrimToSize();
-
- q.Clear();
- Console.WriteLine();
- Console.WriteLine("Count : {0}", q.Count);
- Console.ReadKey();
- }
- }
- }
Output