Codecademy Logo

C# Collections

In C#, collections are used to store, manage, and manipulate groups of related objects efficiently. There are many types of collections provided in C#, including:

  • Arrays and Lists
  • Linked Lists
  • Dictionaries and Key-Value Pairs
  • Sets and Unique Collections
  • Queues and Stacks
  • Sorted Collections
// Below is an example of one of the collection types in C#
List<string> data = new List<string> { "primitive", "array", "list" };
foreach (string datum in data)
{
Console.WriteLine(datum);
}

In C#, non-generic collections (ArrayList, Hashtable, Queue, Stack) are still available for backward compatibility but are generally replaced by their generic counterparts in modern C# development.

In C#, non-generic collections (ArrayList, Hashtable, Queue, Stack) are still available for backward compatibility but are generally replaced by their generic counterparts in modern C# development.

// This shows the non-generic ArrayList object
ArrayList myArrayList = new ArrayList();
myArrayList.Add("A");
myArrayList.Add("B");
myArrayList.Add("C");
//This shows the preferred use of the generic List<T> object
List<string> myList = new List<string>();
myList.Add("A");
myList.Add("B");
myList.Add("C");

In C#, Queue<T> and Stack<T> are specialized collections that follow FIFO (First-In-First-Out) and LIFO (Last-In-First-Out) principles respectively.

In C#, Queue<T> and Stack<T> are specialized collections that follow FIFO (First-In-First-Out) and LIFO (Last-In-First-Out) principles respectively.

// Creating a new Stack
Stack<int> stack = new Stack<int>();
// Adding elements to the Stack
stack.Push(1); // Stack: 1
stack.Push(2); // Stack: 1, 2
stack.Push(3); // Stack: 1, 2, 3
// Removing elements from the Stack
stack.Pop(); // Returns 3, Stack: 1, 2
// Subsequent Pop() operations will return 2 and then 1
// When the stack is empty, Pop() will throw an InvalidOperationException

In C#, the System.Collections.Generic namespace provides a range of collection types including List<T> and arrays, offering flexible and efficient ways to store and manipulate data.

In C#, the System.Collections.Generic namespace provides a range of collection types including List<T> and arrays, offering flexible and efficient ways to store and manipulate data.

Collection types include:

  • List<T>
  • Dictionary<TKey,TValue>
  • LinkedList<T>
  • Queue<T>
  • SortedList<T>
  • Stack<T>
// Example of using List<T> including the proper namespace.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");
Console.WriteLine(names[1]); // Output: Bob
}
}

In C#, LinkedList<T> provides efficient insertion and deletion of elements, particularly useful for scenarios requiring frequent data manipulation.

In C#, LinkedList<T> provides efficient insertion and deletion of elements, particularly useful for scenarios requiring frequent data manipulation.

// Creating a linked list
LinkedList<int> linkedNumbers = new LinkedList<int>();
// Adding elements to the linked list
linkedNumbers.AddLast(1); // Add 1 to the end of the list
linkedNumbers.AddLast(2); // List: 1 -> 2
linkedNumbers.AddLast(3); // List: 1 -> 2 -> 3
linkedNumbers.AddFirst(0); // List: 0 -> 1 -> 2 -> 3
// Removing elements from the linked list
linkedNumbers.RemoveLast(); // List: 0 -> 1 -> 2
linkedNumbers.RemoveFirst(); // List: 1 -> 2
// Adding an element after a paticular node in the linked list
LinkedListNode<int> node = linkedNumbers.Find(2); // Find the node with value 2
if (node != null)
{
linkedNumbers.AddAfter(node, 4); // List: 1 -> 2 -> 4
// Once the node is found, adding an element after or before it is O(1)
}

In C#, SortedList<TKey, TValue> and SortedDictionary<TKey, TValue> automatically maintain their elements in sorted order based on the key.

In C#, SortedList<TKey, TValue> and SortedDictionary<TKey, TValue> automatically maintain their elements in sorted order based on the key.

// Adding elements to a sorted dictionary
SortedDictionary<string, int> sortedDictionary = new SortedDictionary<string, int>();
sortedDictionary.Add("Alice", 95);
sortedDictionary.Add("Bob", 85);
sortedDictionary.Add("Charlie", 90);
// Retriving the ordered items from the sorted dictionary
foreach (KeyValuePair<string, int> pair in sortedDictionary)
{
Console.WriteLine(pair.Key + ": " + pair.Value);
// Output:
// Alice: 95
// Bob: 85
// Charlie: 90
}

In C#, Dictionary<TKey, TValue> stores key-value pairs, offering fast lookups and unique keys.

In C#, Dictionary<TKey, TValue> stores key-value pairs, offering fast lookups and unique keys.

// Creating a Dictionary
Dictionary<string, int> sensorData = new Dictionary<string, int>();
// Adding values to the Dictionary by key
sensorData["sensor_living_room"] = 10;
sensorData["sensor_bathroom"] = 20;
sensorData["sensor_bedroom"] = 30;
// Retriving values from the Dictionary by key
int livingRoomData = sensorData["sensor_living_room"];
Console.WriteLine("Living Room Sensor Data: " + livingRoomData);
// Output: Living Room Sensor Data: 10

In C#, HashSet<T> is utilized for storing unique elements and performing set operations efficiently.

In C#, HashSet<T> is utilized for storing unique elements and performing set operations efficiently.

// Creating some HashSets
HashSet<int> set1 = new HashSet<int> { 1, 2, 3, 4, 5 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5, 6, 7 };
// Note that these sets share 3, 4, and 5
// 1 and 2 are unique to set1
// 6 and 7 are unique to set2
// Using UnionWth()
set1.UnionWith(set2);
// set1 now contains { 1, 2, 3, 4, 5, 6, 7 }
// Reset set1
set1 = new HashSet<int> { 1, 2, 3, 4, 5 };
// Using IntersectWith
set1.IntersectWith(set2);
// set1 now contains { 3, 4, 5 }
// Reset set1
set1 = new HashSet<int> { 1, 2, 3, 4, 5 };
// Using ExceptWith()
set1.ExceptWith(set2);
// set1 now contains { 1, 2 }

In C#, collection expressions provide a concise syntax for initializing arrays, lists, and other collections that support collection initializers, enhancing code readability for certain collection types.

In C#, collection expressions provide a concise syntax for initializing arrays, lists, and other collections that support collection initializers, enhancing code readability for certain collection types.

// Initalizing an Array with a collection expression
int[] numbers = { 1, 2, 3, 4, 5 };
// Initalizing an List with a collection expression
List<string> colors = ["Red", "Green", "Blue"];

Learn more on Codecademy