Collections in C#

Collections in C# standardize the way of which the objects are handled by your program. In other words, it contains a set of classes to contain elements in a generalized manner. With the help of collections, the user can perform several operations on objects like the store, update, delete, retrieve, search, sort etc.

C# divide collection in several classes, some of the common classes are shown below:

System.Collections.Generic Classes

Generic collection in C# is defined in System.Collection.Generic namespace. It provides a generic implementation of standard data structure like linked lists, stacks, queues, and dictionaries. These collections are type-safe because they are generic means only those items that are type-compatible with the type of the collection can be stored in a generic collection, it eliminates accidental type mismatches. Generic collections are defined by the set of interfaces and classes. Below table contains the frequently used classes of the System.Collections.Generic namespace:

Dictionary<TKey,TValue>It stores key/value pairs and provides functionality similar to that found in the non-generic Hashtable class.
List<T>It is a dynamic array that provides functionality similar to that found in the non-generic ArrayList class.
Queue<T>A first-in, first-out list and provides functionality similar to that found in the non-generic Queue class.
SortedList<TKey,TValue>It is a sorted list of key/value pairs and provides functionality similar to that found in the non-generic SortedList class.
Stack<T>It is a first-in, last-out list and provides functionality similar to that found in the non-generic Stack class.
HashSet<T>It is an unordered collection of the unique elements. It prevent duplicates from being inserted in the collection.
LinkedList<T>It allows fast inserting and removing of elements. It implements a classic linked list.

Example:

// C# program to illustrate the concept 
// of generic collection using List<T>
using System;
using System.Collections.Generic;
  
class Tech {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating a List of integers
        List<int> mylist = new List<int>();
  
        // adding items in mylist
        for (int j = 5; j < 10; j++) {
            mylist.Add(j * 3);
        }
  
        // Displaying items of mylist
        // by using foreach loop
        foreach(int items in mylist)
        {
            Console.WriteLine(items);
        }
    }
}

Output:

15
18
21
24
27

System.Collections Classes

Non-Generic collection in C# is defined in System.Collections namespace. It is a general-purpose data structure that works on object references, so it can handle any type of object, but not in a safe-type manner. Non-generic collections are defined by the set of interfaces and classes. Below table contains the frequently used classes of the System.Collections namespace:

ArrayListIt is a dynamic array means the size of the array is not fixed, it can increase and decrease at runtime.
HashtableIt represents a collection of key-and-value pairs that are organized based on the hash code of the key.
QueueIt represents a first-in, first out collection of objects. It is used when you need a first-in, first-out access of items.
StackIt is a linear data structure. It follows LIFO(Last In, First Out) pattern for Input/output.

Example:

// C# to illustrate the concept
// of non-generic collection using Queue
using System;
using System.Collections;
  
class TAS {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Queue
        Queue myQueue = new Queue();
  
        // Inserting the elements into the Queue
        myQueue.Enqueue("C#");
        myQueue.Enqueue("PHP");
        myQueue.Enqueue("Perl");
        myQueue.Enqueue("Java");
        myQueue.Enqueue("C");
  
        // Displaying the count of elements
        // contained in the Queue
        Console.Write("Total number of elements present in the Queue are: ");
  
        Console.WriteLine(myQueue.Count);
  
        // Displaying the beginning element of Queue
        Console.WriteLine("Beginning Item is: " + myQueue.Peek());
    }
}

Output:

Total number of elements present in the Queue are: 5
Beginning Item is: C#

Note: C# also provides some specialized collection that is optimized to work on a specific type of data type and the specialized collection are found in System.Collections.Specialized namespace.

System.Collections.Concurrent

It came in .NET Framework Version 4 and onwards. It provides various threads-safe collection classes that are used in the place of the corresponding types in the System.Collections and System.Collections.Generic namespaces, when multiple threads are accessing the collection simultaneously. The classes present in this collection are:

BlockingCollectionIt provides blocking and bounding capabilities for thread-safe collections that implement
IProducerConsumerCollection.
ConcurrentBagIt represents a thread-safe, an unordered collection of objects.
ConcurrentDictionaryIt represents a thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently.
ConcurrentQueueIt represents a thread-safe first in-first out (FIFO) collection.
ConcurrentStackIt represents a thread-safe last in-first out (LIFO) collection.
OrderablePartitionerIt represents a particular manner of splitting an orderable data source into multiple partitions.
PartitionerIt provides common partitioning strategies for arrays, lists, and enumerables.
PartitionerIt represents a particular manner of splitting a data source into multiple partitions.

Chockalingam