Using Collection Classes in C#


Collections usage in C#

In this article we will demonstrate the usage of the commonly used collection types in System.Collections and System.Collections.Generic namespaces.

We will explore the below list of collection types.

  1. List
  2. ArrayList
  3. Dictionary
  4. HashSet
  5. Stack
  6. Queue

List

List<T> is define in System.Collections.Generic namespace, it is a dynamically resizable sequential list of items. List comes in handy when we do not know the size of the container or container length changes at run time. Some of the important interfaces supported by List<T> are ICollection<T>, IEnumerable<T> and IList<T>.

 

    public class Student
    {
        public string Name
        {
            get;
            set;
        }

        public int ID
        {
            get;
            set;
        }

        public override string ToString()
        {
            return string.Format("Name - {0}, ID - {1}", this.Name, this.ID);
        }
    }
    
    using System;
    using System.Collections.Generic;
    public class Program
    {
        public static void Main()
        {
            // Declare and Initialize an empty List of type int.
            List<int> intList= new List<int>();

            // Add an element.
            intList.Add(20);

            // Add elements by passing IEnumerable<int> collection.
            intList.AddRange(new int[] { 30, 40 });

            Console.WriteLine("Printing Int List.");
            // Enumerate the List and print each item.
            foreach (int item in intList)
            {
                Console.WriteLine(item);
            }

            // Declare and Initialize List of type Student by using Initializing Syntax.
            // The List has three students.
            List<Student> studentList = new List<Student>()
                                        {
                                            new Student(){ Name = "Jack", ID = 11},
                                            new Student(){ Name = "Mary", ID = 22},
                                            new Student(){ Name = "John", ID = 33}
                                        };

            Console.WriteLine();
            Console.WriteLine("Printing Student List.");
            // Iterate and print the list of students.
            // Calls the ToString method of Student type.
            foreach (Student student in studentList)
            {
                Console.WriteLine(student);
            }

            // Remove the element at index 0;
            studentList.RemoveAt(0);

            Console.WriteLine();
            Console.WriteLine("Printing Student List after Removing Element at Index 0.");

            // Iterate and print the list of students.
            // Here we are iterating through the list using indexer.
            for(int index = 0; index < studentList.Count; index++)
            {
                Console.WriteLine(studentList[index]);
            }

            studentList.Insert(0, new Student() { Name = "Sarah", ID = 44 });

            Console.WriteLine();
            Console.WriteLine("Printing Student List after Inserting Element at Index 0.");

            // Iterate and print the list of students.
            // Calls the ToString method of Student type.
            foreach (Student student in studentList)
            {
                Console.WriteLine(student);
            }


            // OUTPUT

            /*
             
            Printing Int List.
            20
            30
            40

            Printing Student List.
            Name - Jack, ID - 11
            Name - Mary, ID - 22
            Name - John, ID - 33

            Printing Student List after Removing Element at Index 0.
            Name - Mary, ID - 22
            Name - John, ID - 33

            Printing Student List after Inserting Element at Index 0.
            Name - Sarah, ID - 44
            Name - Mary, ID - 22
            Name - John, ID - 33
             
             * */
        }
    }

ArrayList

ArrayList is defined in System.Collections namespace, it represents a dynamically resizable collection of object listed in sequential order. ArrayList is useful when you need to store objects of different types in the same container. Some of the important interfaces supported by ArrayList are ICollection, IEnumerable, IList and ICloneable

 

    using System;
    using System.Collections;
    public class Program
    {
        public static void Main()
        {
            // Initialize ArrayList and add an element of type String
            ArrayList arrayList = new ArrayList() { "Some String" };

            // Add a Student type object to the ArrayList.
            arrayList.Add(new Student(){ Name = "John", ID = 11});

            Console.WriteLine("Printing Array List.");

            // Iterate and print the list.
            foreach(object item in arrayList)
            {
                Console.WriteLine(item);
            }

            // Insert 20 at index 0;
            arrayList.Insert(0, 20);

            Console.WriteLine();
            Console.WriteLine("Printing ArrayList after inserting an element at index 0.");

            // Iterate and print the list.
            foreach (object item in arrayList)
            {
                Console.WriteLine(item);
            }

            // Reverse the items in ArrayList.
            arrayList.Reverse();

            Console.WriteLine();
            Console.WriteLine("Printing ArrayList after reversing the elements.");

            // Iterate and print the list.
            foreach (object item in arrayList)
            {
                Console.WriteLine(item);
            }

            // OUTPUT

            /*
             
            Printing Array List.
            Some String
            Name - John, ID - 11

            Printing ArrayList after inserting an element at index 0.
            20
            Some String
            Name - John, ID - 11

            Printing ArrayList after reversing the elements.
            Name - John, ID - 11
            Some String
            20
             
             * */

        }
    }

Dictionary

Dictionary<TKey, TValue> is defined in System.Collections.Genetic namespace, it represents generic collection of keys and values. Some of the important interfaces supported by Dictionary are IEnumerable<T>, ICollection<T> and IDictionary<TKey, TValue>.

 

    using System;
    using System.Collections.Generic;
    public class Program
    {
        public static void Main()
        {
            // Initilaize Dictionary with 2 elements using initialization syntax.
            Dictionary<int, Student> studentDictionary = new Dictionary<int, Student>()
                                                 {                                                                
                                                     {11, new Student(){ID = 11, Name = "John"}},
                                                     {22, new Student(){ID = 22, Name = "Samantha"}}
                                                 };

            Console.WriteLine("Printing Dictonary Values.");

            // Iterate through keys and Print Values.
            foreach(int key in studentDictionary.Keys)
            {
                Console.WriteLine(studentDictionary[key]);
            }

            // Add a new entry to Dictionary.
            studentDictionary.Add(33, new Student() { ID = 33, Name = "Jack" });

            Console.WriteLine();
            Console.WriteLine("Printing Dictionary values after adding a new item.");

            // Iterate through keys and Print Values.
            foreach (int key in studentDictionary.Keys)
            {
                Console.WriteLine(studentDictionary[key]);
            }

            // Removing element with Key 11.
            studentDictionary.Remove(11);
            Console.WriteLine();
            Console.WriteLine("Printing Dictionary values after removing an item.");

            // Iterate through keys and Print Values.
            foreach (int key in studentDictionary.Keys)
            {
                Console.WriteLine(studentDictionary[key]);
            }

            // OUTPUT

            /*
             
            Printing Dictonary Values.
            Name - John, ID - 11
            Name - Samantha, ID - 22

            Printing Dictionary values after adding a new item.
            Name - John, ID - 11
            Name - Samantha, ID - 22
            Name - Jack, ID - 33

            Printing Dictionary values after removing an item.
            Name - Samantha, ID - 22
            Name - Jack, ID - 33
             
             * */

        }
    }

HashSet

HashSet<T> is defined in System.Collections.Generic namespace, it represents a collection of unique values. Some of the important interfaces supported by HashSet are IEnumerable<T>, ISet<T> and ICollection<T>. When comparing for duplicates HashSet uses the default Comparer of the Type T.

 

    using System;
    using System.Collections.Generic;
    public class Program
    {
        public static void Main()
        {
            // Initalize string type HashSet with some duplicate values.
            // "John" is added twice.
            HashSet<string> stringSet = new HashSet<string>() { "John", "John", "Jack", "Sammy" };

            // Print the HashSet.
            // John is displayed only once.
            foreach(string item in stringSet)
            {
                Console.WriteLine(item);
            }

            // OUTPUT

            /*
             
            John
            Jack
            Sammy
             
             * */

        }
    }

Stack

Stack is defined both in System.Collections and System.Collections.Generic namespaces. Here we explore Stack<T> generic type in System.Collections.Generic namespace, it represents a generic implementation of last in, first out (LIFO) list. LIFO means the element added last to the list is the element that can be removed first. Some of the important interfaces supported by Queue<T> are IEnumerable<T> and ICollection.

 

    using System;
    using System.Collections.Generic;
    public class Program
    {
        public static void Main()
        {
            // Initilaize Stack of Type Student.
            Stack<Student> studentStack = new Stack<Student>();

            // Push 3 elements to the Stack.
            studentStack.Push(new Student() { ID = 11, Name = "Jack" });
            studentStack.Push(new Student() { ID = 22, Name = "Sofia" });
            studentStack.Push(new Student() { ID = 33, Name = "Dan"});

            Console.WriteLine("Printing elements in Stack.");

            // Iterate the elements in Stack.
            foreach(Student student in studentStack)
            {
                Console.WriteLine(student);
            }

            // Get the item at the Top of the Stack
            Student topStudent = studentStack.Peek();

            Console.WriteLine();
            Console.WriteLine("Print the Top element of Stack using Peek().");
            Console.WriteLine(topStudent);

            // Remove the Top element of the Stack
            studentStack.Pop();

            Console.WriteLine();
            Console.WriteLine("Printing elements in Stack after removing Top element.");

            // Iterate the elements in Stack.
            foreach (Student student in studentStack)
            {
                Console.WriteLine(student);
            }

            // OUTPUT

            /*
             
            Printing elements in Stack.
            Name - Dan, ID - 33
            Name - Sofia, ID - 22
            Name - Jack, ID - 11

            Print the Top element of Stack using Peek().
            Name - Dan, ID - 33

            Printing elements in Stack after removing Top element.
            Name - Sofia, ID - 22
            Name - Jack, ID - 11
             
             * */

        }
    }

Queue

Queue is defined both in System.Collections and System.Collections.Generic namespaces. Here we explore Queue<T> generic type in System.Collections.Generic namespace, it represents generic implementation of first in, first out (FIFO) list. FIFO means the element added first to the list is the element that can be removed first. Some of the important interfaces supported by Queue<T> are IEnumerable<T> and ICollection.

 

    using System;
    using System.Collections.Generic;
    public class Program
    {
        public static void Main()
        {
            // Initialize Queue of Type string.
            Queue<string> stringQueue = new Queue<string>();

            // Add elements to the Queue
            stringQueue.Enqueue("John");
            stringQueue.Enqueue("Jack");
            stringQueue.Enqueue("Sonia");

            Console.WriteLine("Printing elements in Queue.");
            foreach (string obj in stringQueue)
            {
                Console.WriteLine(obj);
            }

            // Get the item at the beginning of the Queue
            string item = stringQueue.Peek();

            Console.WriteLine();
            Console.WriteLine("Print the Beginnining element of Queue using Peek().");
            Console.WriteLine(item);

            // Dequeue the first element.
            stringQueue.Dequeue();

            Console.WriteLine();
            Console.WriteLine("Printing elements in Queue after a Dequeue");
            foreach (string obj in stringQueue)
            {
                Console.WriteLine(obj);
            }

            // OUTPUT

            /*
             
            Printing elements in Queue.
            John
            Jack
            Sonia

            Print the Beginnining element of Queue using Peek().
            John

            Printing elements in Queue after a Dequeue
            Jack
            Sonia
             
             * */
        }
    }