Skip to main content
ArrayList class in C#

Generic collections in c# with example

In this post, we will be discussing various types of generic collections in C# with the help of examples.

Generic collections in c#

A collection is a similar type of objects grouped together. Every collection class implements the IEnumerable interface, so values from the collection can be accessed using a foreach loop.

Generic Collections in C# #dotnet #csharp #collections Click To Tweet

The System.Collections.Genrics namespace includes following generic collections.

  1. List<T>
  2. SortedList<TKey, TValue>
  3. Hashset<T>
  4. Dictionary<Tkey, TValue>
  5. Stack<T>
  6. Queue<T>

Generic collections in c#

Let’s explore more about these generic collections.

1. List<T>

You might already know about ArrayList in case you don’t recollect refer to our previous post. An ArrayList resizes automatically as it grows. The List collection is the same as an ArrayList except for that List is a generic collection whereas ArrayList is a non-generic collection.

List<T> can be initialized in the following two ways.

List<int> intList = new List<int>();

//Or

IList<int> intList = new List<int>();

Few more features of this collection are:

  1. List<T> is ideal for storing and retrieving a large number of elements.
  2. LINQ can be used to query List<T> collection.
  3. List<T> can store multiple null and duplicate elements.

Methods which can be used with List<T> collection

Add(), AddRange(), BinarySearch(), Clear(), Contains(), Find(), Insert(), Sort(), Remove(), RemoveAt() methods.


IList<int> numbers = new List<int>() { 10, 20, 30 };

foreach (var num in numbers)
Console.WriteLine(num);

Output:

10
20
30

2. SortedList<TKey, TValue>

SortedList stores key and value pairs. It automatically arranges elements in ascending order of key by default. C# includes both, generic and non-generic SortedList collection.

Generic SortedList<TKey,TValue> can be initialized as:

SortedList<int,string> mySortedList = new SortedList<int,string>();

Few more features of this collection are:

  1. SortedList stores the key-value pairs in ascending order of the key.
  2. Generic SortedList stores keys and values of specified data types. So no need for casting.
  3. An individual value can be accessed using an indexer.

Methods which can be used with SortedList<TKey,TValue> collection

Add(), Remove(), RemoveAt(), ContainsKey(), ContainsValue(), Clear(), IndexOfKey(), IndexOfValue(), TryGetValue() methods.

3. Hashset<T>

Hashset<T> contains non-duplicate elements. It eliminates duplicate elements.

Below is an example program using Hashset<T>:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] colors =
        {
            "red",
            "blue",
            "green",
            "yellow",
            "red",
            "green"
        };

        Console.WriteLine(string.Join(",", colors));

        // Use HashSet constructor to ensure unique strings.
        var hash = new HashSet<string>(colors);

        // Convert to array of strings again.
        string[] distinctColors = hash.ToArray();

        // Display the resulting array.
        Console.WriteLine(string.Join(",", distinctColors));
    }
}

Output:

red,blue,green,yellow,red,green
red,blue,green,yellow

4. Dictionary<TKey, TValue>

Dictionary<TKey, TValue> is a generic collection included in the System.Collection.Generics namespace. TKey denotes the type of key and TValue is the type of TValue.

Dictionary can be initialized with a variable of IDictionary<Tkey, TValue> interface as well as with a Dictionary<TKey, Tvalue> class:


IDictionary<int, string> dict = new Dictionary<int, string>();

//OR

Dictionary<int, string> dict = new Dictionary<int, string>();

5. Stack<T>

Stack allows you to get value in Last In First Out(LIFO) principle and uses Push()method to add items to the collections and Pop() method to remove any item from the collections. C# includes both, generic and non-generic Stack. For more on Stack, refer here.

6. Queue<T>

Queue allows you to get value in First In First Out (FIFO) principle and uses Enqueue() method to add items to the collections and Dequeue() method to remove any item from the collections. Both generic and non-generic Queue exists in C#. For more on Queue, refer this post.

You can also have a quick read about Non-Generic collections in .NET.

That’s all for now. Thanks for reading and let me know your valuable comments if any.

Like this post? Don’t forget to share it!

This is a guest post by Dipendra. If you would like to write for DotnetCrunch, check our guest posting guidelines.

Was this article worth reading? Share it with fellow developers too.

Dipendra Shekhawat

Hey Reader! I am a full time software developer and part time blogger from Pune, India. I write about technologies like WordPress, ASP.NET, C#, JQuery, HTML, CSS, AJAX, WCF, Web Services. For more you can refer to my blog - http://dipendrashekhawat.com