Collections in C# .NET

In this post, we’ll look over how to use the most common collections in C# such as queue, stack, ArrayList, hashtable, and SortedList. We’ll also look at the methods they provide.

Collections in C#
C# Collections types

Collections in C#

Collections in C# are a predefined set of classes that are available in the System.Collections namespace for storing multiple items in a single unit. Collections can be used to perform multiple operations on objects such as storing, updating, deleting, retrieving, searching, and sorting.
Collections are used to work with a group of related objects that can dynamically grow or shrink when objects are added or deleted based on our needs.

Non-generic collections such as C# Stack, Queue, HashTable, ArrayList, and SortedList are not strongly typed and store data as objects, so retrieving the value from them involves boxing and unboxing.

In non-generic collections, each element can represent a value of a different data type. The collection size is not fixed. You can add or remove items from the collection at runtime.

C# Collections Workflow

The Collections in C# are divided into several classes, some of which are represented in the picture below:

C# Collections
C# Collections

C# Queue

In C#, The Queue collection represents a FIFO (First In, First Out) collection of objects. The first element of the queue is the first one to be removed. Adding an item to a queue is called an enqueue, and removing an item is called a dequeue.

The queue process flow in the C# programming language is demonstrated in the image below.

C# Queue Collection
C# Queue Collection

C# Queue Declaration

In C #, you can use both generic and non-generic queue types to create object instances for queue collections.

1. By using the namespace System.Collections.Generic;

Queue<int> intQueue = new Queue<int>(); // Generic Queue

2. By using the namespace System.Collections;

 Queue queueCollection = new Queue(); // Non Generic Queue

In this article, we will only discuss non-generic queue collections.

C# Queue Common Methods and Properties

The Enqueue method is used to add elements at the end of the queue collection:

using System;
using System.Collections;
namespace QueueExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Queue queue = new Queue();

            queue.Enqueue(101);
            queue.Enqueue("Shekh Ali");
            queue.Enqueue(20.5f);

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

            Console.ReadLine();
        }
    }

   // Output:
   // 101
   // Shekh Ali
   // 20.5
}

The Peek method is used to return the first element of the queue collection:

Console.WriteLine($" Element is : { queue.Peek()}");  
// Output:
// 101

The queue Dequeue method is used to remove and return an element from the beginning of the queue collection.

using System;
using System.Collections;
namespace QueueExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Queue queue = new Queue();
            queue.Enqueue(101);
            queue.Enqueue("Shekh Ali");
            queue.Enqueue(20.5f);

            // Example of Dequeue method

            Console.WriteLine("Removing some values ");
            Console.WriteLine($" Element is : { queue.Dequeue()}");

            Console.WriteLine("Removing some values ");
            Console.WriteLine($" Element is : { queue.Dequeue()}");

            Console.ReadLine();
        }
    }
    // Output:
    // Removing some values
    // Element is : 101
    // Removing some values
    // Element is : Shekh Ali
}

The Clear method is used to remove all the elements from a queue collection.

 // Example of Clear() method
 Console.WriteLine($"Total elements before clear : {queue.Count} ");

 queue.Clear();

Console.WriteLine($"Total elements after clear : {queue.Count} ");
 // Output:
 // Total elements before clear : 3
 // Total elements after clear : 0

C# Stack

In C#, Stack is a linear data structure that uses the LIFO (last in, first out) concept for input/output operations. Adding an item on top of the stack is called push and removing an item from the stack is called pop.

C# Stack
C# Stack collection in C#

Example: C# Stack

using System;
using System.Collections;
namespace StackExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack stack = new Stack();

            // Adding (Pushing) elements to the stack

            stack.Push(1);
            stack.Push(2);
            stack.Push(3);
            stack.Push(4);
            stack.Push(5);


            // Displaying stack elements
            foreach (Object obj in stack)
            {
                Console.Write($" { obj }");
            }

            // Access Stack last (top-most) inserted element
            Console.WriteLine($"\n Peek Element : {stack.Peek()}");

            // Removing (Popping) an element from the stack
            stack.Pop();

            Console.WriteLine("\n Elements after pop operation"); 

            foreach (Object obj in stack)
            {
                Console.Write($" { obj }");
            }

            Console.ReadKey();
        }
    }
    // Output:
    // 54321
    // Peek Element : 5
    //Elements after pop operation
    // 4321
}

The following are the various commonly used methods used in Stack.

C# Stack MethodDescription
1. PushThe Push method is used to insert an element at the top of the stack collection.
2. PopThe Pop method removes an element from the top of the stack collection and returns it.
3. PeekThe Peek method is used to return an element from the top of the stack without removing it.
4. ClearThe Clear method is used to remove all the elements from the stack.
5. CloneThe Clone method creates a shallow copy of the Stack.
6. ContainsThe Contains method checks if the element is in the Stack.
C# Stack Collection

C# HashTable

A Hashtable is a special collection that is used to store key-value items of different data types that are organized based on the hash code of the key.
When adding items to the hashtable, make sure there are no duplicate keys, as the hashtable can contain duplicate values. However, the keys must be unique in order to identify the values in the hashtable.

Hashtable is a non-generic collection type available in the System.Collections namespace.

Key:A unique integer is used for indexing the value in the hashtable.
Value:Data that is associated with the key.
C# HashTable key/value collection

C# HashTable Declaration

The following is the syntax to declare a Hashtable.

Hashtable ht = new Hashtable();

C# HashTable Examples

The example below demonstrates how to create, initialize, and perform various actions on a Hashtable, as well as how to display its keys and values.

using System;
using System.Collections;
namespace HashTableExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating a hashtable variable
            Hashtable hashtable = new Hashtable();

            // Adding Country Codes

            hashtable.Add("91", "India");
            hashtable.Add("92", "Pakistan");
            hashtable.Add("1", "United States");
            hashtable.Add("33", "France");
            hashtable.Add("61", "Australia");

            // ContainsKey: to Check if key is available in the hashtable
            if (hashtable.ContainsKey("91"))
            {
                Console.WriteLine(" Key (91) is available in the list");
            }

            // ContainsValue: to Check if value is available
            if (hashtable.ContainsValue("India"))
            {
                Console.WriteLine(" Value (India) is available in the list");
            }

            // To remove an item from a hashtable based on its key.
            hashtable.Remove("92");


            // Getting the collection of the keys.
            ICollection key = hashtable.Keys;

            // Displaying the keys and values
            foreach (string k in key)
            {
                Console.WriteLine($" {k} : { hashtable[k]}");
            }
            Console.ReadKey();
        }
    }

    // Output:
    // Key (91) is available in the list
    // Value(India) is available in the list
    // 33 : France
    // 1 : United States
    // 61 : Australia
    // 91 : India
}

The following are the various commonly used methods used in HashTable.

C# Hastable MethodDescription
1. AddThe Add method is used to insert an element with the specified key and value.
2. RemoveThe Remove method is used to remove an element with a specified key from the hashtable collection.
3. Clear The Clear method is used to remove all the elements from the hashtable
4. Clone The Clone method creates a shallow copy of the hashtable.
5. Contains The Contains method checks if the element is in the Hashtable.
6. ContainsKeyThe ContainsKey method determines whether the Hashtable contains a specific key or not.
7. ContainsValueThe ContainsValue method determines whether the Hashtable contains a specific value or not.
C# HashTable Collection

C# ArrayList

ArrayList is the non-generic type of collection that is defined in the System.Collections namespace. It is a dynamic array that can hold the data of multiple data types. ArrayList is very similar to an array, but it can be dynamically grown or shrunk when objects are added or deleted based on our needs.

Example: C# ArrayList

The following is an example of an ArrayList in C# Programming.

using System;
using System.Collections;
namespace ArrayListExample
{
    class Program
    {
        static void Main(string[] args)
        {
           // Creating an arraylist collection
            ArrayList arrayList = new ArrayList();   

            // Adding elements in the ArrayList
            arrayList.Add("Hello");             
            arrayList.Add(10);
            arrayList.Add(20);
            arrayList.Add(30);
            arrayList.Add(40.5f);
            arrayList.Add(60);
            arrayList.Add(32);
            
            // Removing element
            arrayList.Remove(32);

            //Creating new arraylist
            ArrayList arrayList2 = new ArrayList() { "Shekh", "Ali" };

            // Adding arrayList2 to existing arrayList
            arrayList.AddRange(arrayList2);
            

            // Inserting element into arraylist
            arrayList.Insert(1, "World");

            // Access elements by index Position
            Console.WriteLine($"Element at Index 0:{arrayList[0]}");

            // Count property
            Console.WriteLine($"ArrayList Total Count:{arrayList.Count}");

            

            // Accessing ArrayList Elements Using Foreach loop
            foreach (object obj in arrayList)
            {
                Console.WriteLine(obj);

            }

            // Removing an element at index 0 from ArrayList
            arrayList.RemoveAt(1);

            Console.WriteLine("** Removing 5 elements starting from index 1 **");
            arrayList.RemoveRange(1, 5);

            foreach (object obj in arrayList)
            {
                Console.WriteLine(obj);

            }
            Console.ReadLine();
        }
    }
}

Following is the output of various methods and properties of ArrayList.

C# ArrayList Example
C# ArrayList Example

C# SortedList

The SortedList class represents a collection of key/value pairs that by default sort items by key in ascending order. A SortedList is a combination of an array and a hash table that allows you to access an element either by a key or an index. C# contains both generic and non-generic SortedList collections in System.Collections.Generic and System. Collections namespace respectively.

C# SortedList Characteristics:

  • A SortedList key must be unique and cannot be null.
  • A SortedList value can be null or duplicate.
  • A non-generic SortedList Comes under System.Collections namespace.
  • A SortedList indexer accepts a key to return the value associated with it(Example: sortedList[key]).

Example: C# SortedList

using System;
using System.Collections;
namespace SortedListExample
{
    class Program
    {
        static void Main(string[] args)
        {
                // Creating SortedList
                SortedList sortedList = new SortedList();


               // Adding names in SortedList
                sortedList.Add("01", "Shekh Ali");
                sortedList.Add("02", "Kalpana");
                sortedList.Add("03", "Priyanka");
                sortedList.Add("04", "Robert");
                sortedList.Add("05", "Minhaj Ali");
                sortedList.Add("06", "Suhail Khan");
               

                if (sortedList.ContainsValue("Shekh Ali"))
                {
                    Console.WriteLine("This name is already in the SortedList");
                }
                else
                {
                    sortedList.Add("07", "Shekh Ali");
                }

                // Getting keys collection. 
                ICollection keys = sortedList.Keys;

                foreach (string key in keys)
                {
                    Console.WriteLine($"{key} : {sortedList[key]}");
                }
            Console.ReadLine();
        }
        //Output:
        //This name is already in the SortedList
        //01 : Shekh Ali
        //02 : Kalpana
        //03 : Priyanka
        //04 : Robert
        //05 : Minhaj Ali
        //06 : Suhail Khan
    }
}

FAQ‘s

Q: What are collections in C#?

Ans: Collections in C# are a predefined set of classes that are available in the System.Collections namespace to store multiple items in a single unit.
Collections are used to work with a group of related objects that can dynamically grow or shrink when objects are added or deleted based on our needs.
Non-generic collections such as Stack, Queue, HashTable, ArrayList, and SortedList are not strongly typed and store data as objects, so retrieving the value from them involves boxing and unboxing.

Q: What is the difference between collection and array?

Ans: Arrays are fixed in size, which means that once you create an array, you will not be able to resize it to meet your needs.
Collections, on the other hand, are growable in nature, They can dynamically grow or shrink when objects are added or deleted as needed.

Q: Is ArrayList is a generic collection in C#?

Ans: In C#, an ArrayList is a non-generic collection of objects whose size increases dynamically. It is the same as an array, except that it grows dynamically in size.
ArrayList allows you to add data of any data type without knowing the type and size of the data.

Q: What is the difference between Array and Arraylist Collections in C#?

Ans: The size of an Array is fixed and cannot be changed dynamically, while the size of an ArrayList can be changed dynamically when items are added or deleted.
Array class is available in System.Array namespace, whereas ArrayList belongs to the System.Collections namespace.

Q: What is the generic collection in C#?

Ans: A generic collection is a strongly typed collection of the same type of object that allows us to avoid type mismatches at runtime. It also improves performance by avoiding boxing and unboxing.

Q: How many types of collections are there in C#?

Ans: There are two types of collections available in C#: non-generic and generic collections.
The non-generic collection types are available in System.Collections namespace while generic collection types are available in System.Collections.Generic namespace.

References MSDN: Collections (C#)

Thank you for taking the time to read the blog about “Collections in C#“, if you find it interesting, please put your comment, and share it with others. Thanks.

You Might Like:

Leave a Comment