Table of contents
1.
Introduction
2.
What are the collections in C#?
3.
Types of Collections in C#
3.1.
System.Collections.Generic
3.2.
System.Collections
3.3.
System.Collections.Concurrent
4.
Frequently Asked Questions
4.1.
Which collection is faster in C#?
4.2.
Is collection a class in C#?
4.3.
How to order a collection in C#?
4.4.
How to return a collection in C#?
4.5.
How to add to a collection in C#?
5.
Conclusion
Last Updated: Nov 3, 2024
Easy

Collections in C#

Author Yashesvinee V
0 upvote

Introduction

In C#, data can be stored using collections or arrays. While arrays in C# have a fixed size and only hold a specified number of elements, C# collections are much more flexible. They can dynamically grow and shrink as elements are added or removed. C# collections provide organized classes for managing data, including support for stacks, queues, lists, and hash tables. This flexibility and structure make collections an essential feature for handling dynamic data in C#.

Collections in C#

What are the collections in C#?

In C#, collections are specialized classes used to manage groups of related objects. Unlike arrays, collections can dynamically resize as elements are added or removed, making them versatile for handling data. The main types of collections in C# are:

  1. List: A generic collection that allows duplicate elements and maintains the order of items.
     
  2. Dictionary: Stores key-value pairs and provides fast access using keys.
     
  3. Queue: Follows a First-In-First-Out (FIFO) approach, suitable for handling sequential tasks.
     
  4. Stack: Follows a Last-In-First-Out (LIFO) order, often used for reverse processing.
     
  5. HashSet: A collection of unique items, which prevents duplicates and provides fast lookup.
     

These collections are part of the System.Collections and System.Collections.Generic namespaces, and they offer built-in methods for adding, removing, and managing elements effectively.

Types of Collections in C#

A collection is a class whose instance must be declared before adding elements to that collection. Collections help perform various data manipulation operations like insertion, deletion, sorting, searching, etc. Collections in C# are composed of many classes. The most common ones are

  • System.Collections.Generic
     
  • System.Collections
     
  • System.Collections.Concurrent

System.Collections.Generic

Generic Collections work on a specific data type. It is used when we want to build a collection of elements of a single data type. This enforces type safety so that no other data type can be added randomly. Hence, we do not have to determine an element’s data type or convert it during retrieval.

The following table shows some of the frequently used classes of the System.Collections.Generic namespace.

Here's the table with basic formatting:

ClassDescription
Dictionary<TKey, TValue>Represents a collection of key-value pairs. Values can be accessed using their corresponding unique keys.
List<T>Represents a list of objects whose contents can be accessed using the index position.
Queue<T>Represents a first-in-first-out (FIFO) collection of objects.
SortedList<TKey, TValue>Represents a collection of key-value pairs whose keys are sorted based on an IComparer interface that compares two objects.
Stack<T>Represents a last-in-first-out (LIFO) collection of objects.

 

Example:

using System;
using System.Collections.Generic;

class NewList
{
    public static void Main(String[] args)
    {
       // Creating a List of integers
       List<int> l = new List<int>();

       // adding items
       for (int j = 1; j <=5; j++) 
       {
         l.Add(j);
       }

       // Displaying list elements
       foreach(int items in l)
       {
         Console.WriteLine(items);
       }
   }
}

 

Output:

1
2
3
4
5

System.Collections

System.Collections stores elements as objects instead of a particular data type. It is a general-purpose data structure that works on any type of object but is not safe. Hence, it is recommended to use Generic collections instead of non-generic ones.

Some common classes of the System.Collections namespace are:

ClassDescription
ArrayListRepresents a collection of objects whose size can be dynamically changed.
HashTableRepresents a collection of objects organized based on hash keys.
QueueRepresents a first-in-first-out (FIFO) collection of objects.
StackRepresents a last-in-first-out (LIFO) collection of objects.
BitArrayRepresents an array of bits containing 0 and 1.

 

Example:

using System;
using System.Collections;

class NewArraylist
{
    public static void Main()
    {
       // Creating an ArrayList
       ArrayList l = new ArrayList();

       // Adding elements 
       l.Add("Hello");
       l.Add("World");

       Console.WriteLine("Count : " + l.Count);

       foreach(string i in l)
       {
         Console.WriteLine(i);
       }
   }
}

 

Output:

Count : 2
Hello
World

System.Collections.Concurrent

It provides various threads-safe collection classes that are used when multiple threads access a collection simultaneously. Some classes of the System.Collections.Concurrent are:

ClassDescription
ConcurrentDictionaryIt represents a thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently.
ConcurrentStackIt represents a thread-safe, last-in-first out (LIFO) collection
ConcurrentQueueIt represents a thread-safe, first-in-first out (FIFO) collection
ConcurrentBagIt represents a thread-safe, unordered collection of objects
PartitionerIt provides partitoning strategies for arrays, lists, and enumerables. 


Also check out this article - singleton design pattern in c#

Frequently Asked Questions

Which collection is faster in C#?

List<T> is generally faster for accessing elements by index, while Dictionary<TKey, TValue> is faster for key-based lookups.

Is collection a class in C#?

Yes, in C#, Collection<T> is a class in the System.Collections.ObjectModel namespace, providing a base class for collections.

How to order a collection in C#?

Use OrderBy or OrderByDescending methods from System.Linq to sort a collection based on specified criteria.

How to return a collection in C#?

Return a collection in C# by specifying the collection type as the return type, e.g., List<T> or IEnumerable<T>.

How to add to a collection in C#?

Use the Add method to insert elements into a collection like List<T>, Dictionary<TKey, TValue>, or other mutable collections.

Conclusion

This article extensively discusses Collections in C#. We hope that this blog has helped you enhance your knowledge about the different kinds of Collections in C#. If you would like to learn more, check out our articles on the Coding Ninjas Library. Do upvote our blog to help other ninjas grow. Happy Coding!

Check out this problem - Queue Implementation

Related Links:

Interfaces in C#

Dictionary in C#

Live masterclass