Different Collections in C#

There are different types of collections available in C#; based on the requirement, you can use them. The available collections in C# are Dictionaries, Lists, Stacks, Queues, Sets, and many others.

Dictionaries: When you want to maintain key, value pair, dictionary is a good option in C#. Dictionary has to implement the interface IDictionary<TKey, TValue>. That means in dictionaries, key and value can be any type like string, int…etc. 

namespace CSharpCollections
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> countries = new Dictionary<int, string>();

            countries.Add(1, "United States");
            countries.Add(2, "United Kingdom");
            countries.Add(3, "United France");
        }
    }
}

Here we declared the dictionary whose key of int type and value is of string type. In the dictionary, the key should be unique and value can be duplicate. 

Lists: Lists are the most commonly used collections in C#, and these are generated from System.Collections.Generic namespace. Each item in a List has an index that is unique, and it starts from 0. List items can be any type defined by T.

namespace CSharpCollections
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> listString = new List<string>();

            //Add string type values to list
            listString.Add("A");
            listString.Add("B");
            listString.Add("C");

            //access list item by index
            string sAlphabet = listString[1];
        }
    }
}

Stacks: Whenever we want to implement Last In First Out (LIFO) behavior, we can use stacks. From the stack, we can remove only one item at once from the top. Even we can add only one item on top. 

Queues: Queues also the same as stack, but we will use Queue whenever we want First In First Out (FIFO) behavior. That means we can access the item in the same order how they added. 

Sets: Sets are useful whenever you want to perform set operations between two collections.