Generic Collections in C# with Examples

6 Generic Collections in C# with Examples

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

Generic Collections in C#

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

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

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

6 Generic Collections in C# with Examples

Let’s explore more about these generic collections in C#.

1. List<T>

You might already know about ArrayList in case you don’t recollect, refer to our post on Collections in C# – ArrayList. An ArrayList resizes automatically as it grows.

The List collection is the same as an ArrayList except 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()
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 collections.

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()

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 to our post on Collections in C# – Stack.

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 to Collections in C# – Queues.

Further Reading

That was a short and easy explanation for all these generic collections in C#. If you want to further read, you may refer to the official documentation from Microsoft.

C# Mastery – Mosh Hamedani

One of the best courses to master your C# skills right from level zero. This series is divided into 4 sections:

  1. C# Basics
  2. C# Intermediate
  3. C# Advanced
  4. Unit Testing for C# Developers

csharp mastery course mosh

Conclusion

That’s all for the Generic Collections in C# with examples topic. Thanks for reading and let me know your valuable comments if any.

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

Was this post on “generic collections in c#” worth reading? Share it with fellow developers too.

Happy Coding { }

Disclaimer: Most of the content is FREE. But some resources may contain affiliate links. When you purchase, I may receive a commission from the seller, at no extra cost to yourself.

Share with your friends:

Leave a Comment

Your email address will not be published. Required fields are marked *