logo codesdope

C# Collections


In the previous chapter, we learned about arrays but the problem with an array is that the size of an array is fixed and we can't change the size of an array dynamically during the program.

This problem is solved by using collections. We can use a collection and increase and reduce its size whenever we want. There are different types of collections available in C# and we are going to learn about some of them in this chapter.

A collection is basically a class. You will learn more about classes in further chapters. So, let's foucs on collection in this chapter.

List


Similar to arrays, a List is also used to store collection of elements but its size is dynamic and we don't need to define the size of a List while making it.

The syntax for creating a List is:

List<Type> listName = new List<Type>();

Here, listName is the name of the List we are creating and Type is the data type like int, string, etc. We can also create a List of objects of classes.

Add and Remove


We add a new element to a list using Add method and remove any item using Remove function. Let's look at an example.

using System;
using System.Collections.Generic;

class Test
{
  static void Main(string[] args)
  {
    List<<int> a = new List<int>();
    a.Add(1);
    a.Add(2);
    a.Add(3);
    a.Add(4);
    a.Add(5);

    foreach(var i in a)
      Console.WriteLine(i);

    a.Remove(3);

    foreach(var i in a)
      Console.WriteLine(i);
  }
}
Output
1
2
3
4
5
1
2
4
5

List is present in System.Collection.Generic. That's why we have included that in the beginning - using System.Collections.Generic;.

We can also initialize a List while declaring it.

List<Type> listName = new List<Type>(){element1, element2};

This will make a List with element1 and element2 inside it. Let's take an example.

using System;
using System.Collections.Generic;

class Test
{
  static void Main(string[] args)
  {
    List<string> a = new List<string>(){"John", "Cena"};

    foreach(var i in a)
      Console.WriteLine(i);
  }
}
Output
John
Cena

We can also access the elements of a List using an index as we do with an array. Let's take an example.

using System;
using System.Collections.Generic;

class Test
{
  static void Main(string[] args)
  {
    List<string> a = new List<string>(){"John", "Cena"};

    Console.WriteLine(a[0]);
  }
}
Output
John

Insert


Insert method is used to insert an element at a specific index in a List. Let's look at the following example.

using System;
using System.Collections.Generic;

class Test
{
  static void Main(string[] args)
  {
    List<string> a = new List<string>(){"John", "Cena"};

    a.Insert(2, "CodesDope");

    foreach(var i in a)
      Console.WriteLine(i);
  }
}
Output
John
Cena
CodesDope

Count


We can use Count property on a List to get the number of elements inside a List.

using System;
using System.Collections.Generic;

class Test
{
  static void Main(string[] args)
  {
    List<string> a = new List<string>(){"John", "Cena"};

    for(var i=0; i<a.Count; i++)
    {
      Console.WriteLine(a[i]);
    }
  }
}
Output
John
Cena

Contains


Contains method is used to check if an element is present inside a List or not.

using System;
using System.Collections.Generic;

class Test
{
  static void Main(string[] args)
  {
    List<string> a = new List<string>(){"John", "Cena"};

    Console.WriteLine(a.Contains("John"));
    Console.WriteLine(a.Contains("CodesDope"));
  }
}
Output
True
False

You can learn more about List by going through the offical documentation.

Queue


A Queue works with FIFO (First In First Out) policy. It means that an element which is added first will be removed first. We use Enqueue and Dequeue methods to add and remove elements from a Queue respectively.

using System;
using System.Collections.Generic;

class Test
{
  static void Main(string[] args)
  {
    Queue<string> q = new Queue<string>();

    q.Enqueue("a");
    q.Enqueue("b");

    foreach(var i in q)
      Console.WriteLine(i);

    q.Dequeue();
    Console.WriteLine(); //to print blank line

    foreach(var i in q)
      Console.WriteLine(i);
  }
}
</string></string>
Output
a
b

b

A queue also has Count property and Contains method.

We can use Peek method to get the firstly added item (which can be removed by Dequeue) of a queue (without removing it).

using System;
using System.Collections.Generic;

class Test
{
  static void Main(string[] args)
  {
    Queue<string> q = new Queue<string>();

    q.Enqueue("a");
    q.Enqueue("b");

    Console.WriteLine(q.Peek());
  }
}
Output
a

Stack


A Stack works with LIFO (Last In First Out) policy. It means that an element which is added last will be removed first. We use Push and Pop methods to add and remove elements from a Stack respectively.

using System;
using System.Collections.Generic;

class Test
{
  static void Main(string[] args)
  {
    Stack<string> s = new Stack<string>();

    s.Push("a");
    s.Push("b");

    foreach(var i in s)
      Console.WriteLine(i);

    s.Pop();
    Console.WriteLine(); //to print blank line

    foreach(var i in s)
      Console.WriteLine(i);
  }
}
Output
b
a

a

A Stack also has Count property and Contains method. We can also use Peek method to get the last added item from a stack (without removing it).

using System;
using System.Collections.Generic;

class Test
{
  static void Main(string[] args)
  {
    Stack<string> s = new Stack<string>();

    s.Push("a");
    s.Push("b");

    Console.WriteLine(s.Peek());
  }
}
Output
b

HashSet


A HashSet is like a List but doesn't store dublicate items.

using System;
using System.Collections.Generic;

class Test
{
  static void Main(string[] args)
  {
    HashSet<string> h = new HashSet<string>();

    h.Add("a");
    h.Add("b");
    h.Add("a");

    foreach(var i in h)
      Console.WriteLine(i);
  }
}
Output
a
b

As you can see in the above example, "a" was already present in the HashSet, so it was not added again.

We can also use Count property and methods like Remove, Contains, etc. on a HashSet.

You can see full detail about a HashSet form the official documentation

SortedSet


A SortedSet is used to store items in ascending order. Let's take an example.

using System;
using System.Collections.Generic;

class Test
{
  static void Main(string[] args)
  {
    SortedSet<string> s = new SortedSet<string>();

    s.Add("c");
    s.Add("b");
    s.Add("d");
    s.Add("a");
    s.Add("e");

    foreach(var i in s)
      Console.WriteLine(i);
  }
}
Output
a
b
c
d
e

You can see full detail about a SortedSet from offical documentation.

Dictionary


A Dictionary is used to store values with keys. Suppose, the cost of a Mango is 40, Apple is 30 and Orange is 10. We can store the values 40, 30 and 10 with their respective keys i.e., Mango, Apple and Orange respectively using a Dictionary.

We declare a Dictionary as:

Dictionary<KeyType, ValueType> dictionaryName = new Dictionary<KeyType, ValueType>();

We can access the value of any key k is a Dictionary dict using dict[k]. Let's take an example.

using System;
using System.Collections.Generic;

class Test
{
  static void Main(string[] args)
  {
    Dictionary<string, int> d = new Dictionary<string, int>();

    d.Add("Mango", 40);
    d.Add("Apple", 30);
    d.Add("Orange", 10);

    Console.WriteLine(d["Apple"]);
  }
}
Output
30

Keys and Values


We can use Keys and Values property to get all keys and values respectively of a Dictionary in a collection.

using System;
using System.Collections.Generic;

class Test
{
  static void Main(string[] args)
  {
    Dictionary<string, int> d = new Dictionary<string, int>();

    d.Add("Mango", 40);
    d.Add("Apple", 30);
    d.Add("Orange", 10);

    foreach(var i in d.Keys)
      Console.Write($"{i}\t");
    Console.Write("\n");

    foreach(var i in d.Values)
      Console.Write($"{i}\t");
    Console.Write("\n");
  }
}
Output
Mango  Apple  Orange
4  3  10

SortedList


SortedList is also like a Dictionary but keeps the items sorted according to their keys. Let's look at an example.

using System;
using System.Collections.Generic;

class Test
{
  static void Main(string[] args)
  {
    SortedList<string, int> s = new SortedList<string, int>();

    s.Add("Mango", 40);
    s.Add("Apple", 30);
    s.Add("Orange", 10);

    foreach(KeyValuePair<string, int> i in s)
      Console.WriteLine($"{i.Key} ---> {i.Value}");
  }
}
Output
Apple ---> 30
Mango ---> 40
Orange ---> 10

Download Our App.
BlogsDope App
Get it on Google Play
Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.