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:
// 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);}
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 objectArrayList myArrayList = new ArrayList();myArrayList.Add("A");myArrayList.Add("B");myArrayList.Add("C");//This shows the preferred use of the generic List<T> objectList<string> myList = new List<string>();myList.Add("A");myList.Add("B");myList.Add("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 StackStack<int> stack = new Stack<int>();// Adding elements to the Stackstack.Push(1); // Stack: 1stack.Push(2); // Stack: 1, 2stack.Push(3); // Stack: 1, 2, 3// Removing elements from the Stackstack.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
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}}
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 listLinkedList<int> linkedNumbers = new LinkedList<int>();// Adding elements to the linked listlinkedNumbers.AddLast(1); // Add 1 to the end of the listlinkedNumbers.AddLast(2); // List: 1 -> 2linkedNumbers.AddLast(3); // List: 1 -> 2 -> 3linkedNumbers.AddFirst(0); // List: 0 -> 1 -> 2 -> 3// Removing elements from the linked listlinkedNumbers.RemoveLast(); // List: 0 -> 1 -> 2linkedNumbers.RemoveFirst(); // List: 1 -> 2// Adding an element after a paticular node in the linked listLinkedListNode<int> node = linkedNumbers.Find(2); // Find the node with value 2if (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)}
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 dictionarySortedDictionary<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 dictionaryforeach (KeyValuePair<string, int> pair in sortedDictionary){Console.WriteLine(pair.Key + ": " + pair.Value);// Output:// Alice: 95// Bob: 85// Charlie: 90}
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 DictionaryDictionary<string, int> sensorData = new Dictionary<string, int>();// Adding values to the Dictionary by keysensorData["sensor_living_room"] = 10;sensorData["sensor_bathroom"] = 20;sensorData["sensor_bedroom"] = 30;// Retriving values from the Dictionary by keyint livingRoomData = sensorData["sensor_living_room"];Console.WriteLine("Living Room Sensor Data: " + livingRoomData);// Output: Living Room Sensor Data: 10
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 HashSetsHashSet<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 set1set1 = new HashSet<int> { 1, 2, 3, 4, 5 };// Using IntersectWithset1.IntersectWith(set2);// set1 now contains { 3, 4, 5 }// Reset set1set1 = 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.
// Initalizing an Array with a collection expressionint[] numbers = { 1, 2, 3, 4, 5 };// Initalizing an List with a collection expressionList<string> colors = ["Red", "Green", "Blue"];