Collections in C# with Examples

6 Collections in C# with Examples

In this post, we will be discussing various types of Collections in C# with examples.

What is a Collection in C#?

A collection is a similar type of objects grouped together. A collection is a class, so you must declare an instance of the class before you can add elements to that collection.

Every collection class implements the IEnumerable interface so values from the collection can be accessed using a for each loop.

Collections in C# with Examples

The System.Collections namespace includes the following collections in C#.

  1. ArrayList
  2. SortedList
  3. Hashtable
  4. BitArray
  5. Stack
  6. Queue

Collections in C# with examples

Let us understand these collections in C# with examples.

1. ArrayList

ArrayList stores objects of any type like an array. However, there is no need to specify the size of the ArrayList like with an array as it grows automatically.

Few more features of this collection are:

  • It can store items(elements) of any datatype.
  • resizes automatically as you add the elements.
  • can contain multiple null and duplicate items.

Methods that can be used with ArrayList collection:

  • Add()
  • AddRange()
  • Remove()
  • RemoveRange()
  • Insert()
  • InsertRange()
  • Sort()
  • Reverse()

ArrayList in C# Example:

ArrayList myArryList = new ArrayList();
myArryList .Add("dotnetcrunch");
myArryList .Add(50);
myArryList .Add(10.5);

foreach(var item in myArryList)
Console.WriteLine(item);

Output:

dotnetcrunch
50
10.5

 

2. SortedList

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.

Few highlights for a SortedList Collection:

  • Key must be unique and cannot be null whereas value can be null or duplicate.
  • This collection stores keys and values of any data type. So values need to be cast to the appropriate data type.
  • SortedList indexer accepts a key to return the value associated with it.

SortedList in C# Example:

SortedList sortedList = new SortedList();
sortedList.Add("one", 1);
sortedList.Add("two", 2);

foreach(DictionaryEntry kvp in sortedList )
Console.WriteLine("key: {0}, value: {1}", kvp.Key , kvp.Value );

Output:

key: one, value: 1
key: two, value: 2

 

3. Hashtable

Hashtable stores key and value pairs. It retrieves the values by comparing the hash value of the keys.

Few points to remember for this collection:

  • The key must be unique.
  • The Hashtable key cannot be null whereas the value can be null.
  • Slower in performance than Dictionary collection as it retrieves an item by comparing the hashcode of keys.
  • It uses the default hashcode provider which is an object.GetHashCode(). You can also use a custom hashcode provider.
  • Use DictionaryEntry with foreach statement to iterate Hashtable.

Hashtable in C# Example:

Hashtable hashTable = new Hashtable();
hashTable.Add(dnc, "DotNetCrunch");
hashTable.Add(1.5F, "1.5");
ht.Add(Dc, "Three");

foreach (var key in hashTable.Keys)
Console.WriteLine("{0}, {1}",key , hashTable[key]);

Output:

dnc, DotNetCrunch
1.5, 1.5
Dc, Three

 

4. BitArray

BitArray manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on [1] and false indicates the bit is off [0].

5. Stack

Stack allows you to get value in the 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.

Stack in C# Example:

Stack myStack = new Stack();
myStack.Push("Hello DotnetCrunch!");
myStack.Push(1);
myStack.Push(2);

foreach (var item in myStack)
 Console.Write(item);

Output:

2
1
Hello DotnetCrunch!

 

6. Queue

Queue allows you to get value in the 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#.

Queue in C# Example:

Queue queue = new Queue();
queue.Enqueue(3);
queue.Enqueue("Two");
queue.Enqueue(1);

Console.WriteLine("Number of elements in the Queue: {0}", queue.Count);

while (queue.Count > 0)
Console.WriteLine(queue.Dequeue());

Console.WriteLine("Number of elements in the Queue: {0}", queue.Count);

Output:

Number of elements in the Queue: 3
3
Two
1
Number of elements in the Queue: 0

 

Further Reading

That was a short and easy explanation for all these 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 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 article 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 *