0% found this document useful (0 votes)
13 views

C# collections

The document provides a comprehensive overview of various C# collections, including Arrays, ArrayLists, Lists, LinkedLists, Queues, Stacks, HashSets, SortedSets, Dictionaries, and their concurrent counterparts. Each collection type is described with its main methods, use cases, pros and cons, and tips for usage. This serves as a guide for developers to choose the appropriate collection based on their specific needs and scenarios.

Uploaded by

developer.muneer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

C# collections

The document provides a comprehensive overview of various C# collections, including Arrays, ArrayLists, Lists, LinkedLists, Queues, Stacks, HashSets, SortedSets, Dictionaries, and their concurrent counterparts. Each collection type is described with its main methods, use cases, pros and cons, and tips for usage. This serves as a guide for developers to choose the appropriate collection based on their specific needs and scenarios.

Uploaded by

developer.muneer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

C# Collections

From Arrays to Dictionaries


And Everything In Between

Keivan Damirchi

Include:
● Types of all collections in C#
● Description of each item
● Use case of each
● Examples of each
● Some of the main top methods of each
● Pros and Cons of using each

Collections mentioned:
Array, ArrayList, List, LinkedList, Queue, Stack
SortedSet, SortedDictionary, SortedList, Dictionary
NameValueCollection, ConcurrentBag, ConcurrentQueue
ConcurrentStack, ConcurrentDictionary
Array
An array is a fixed-size collection of elements of the same type. Arrays
are useful when you need to work with a fixed-size collection of
elements, and you know the size of the collection in advance.

Main top Array methods

CopyTo: Copies the elements of the array to another array starting at the specified index.
IndexOf: Returns the index of the first occurrence of the specified value in the array.
Reverse: Reverses the order of the elements in the array.
Sort: Sorts the elements in the array.
Clone: Creates a new array with the same elements as the original array.
BinarySearch: Searches the array for a specified value using a binary search algorithm.

contiguous block provides fast element


Fixed size
of memory access

insertion/deletion of elements is
slow

Tip: Use Array when you have a fixed number of elements and you need to
access them frequently by index.

1
ArrayList
An ArrayList is a dynamically sized collection of objects of any type.
ArrayLists are useful when you need to work with a collection of objects
that can grow or shrink in size.

Main top ArrayList methods

Add: adds an element to the end of the ArrayList.


Remove: removes the first occurrence of a specified object from the ArrayList.
Contains: determines whether an element is in the ArrayList.
ToArray: copies the elements of the ArrayList to a new array.
TrimToSize: sets the capacity of the ArrayList to the actual number of elements it
contains.

Resizable stores elements of


array any type

slower than List<T> due to


boxing/unboxing and type casting

Tip: Use ArrayList when you have a collection of objects whose size can
change dynamically and you need to perform operations like add, remove,
and search frequently.

2
List<T>
A List<T> is a generic dynamically sized collection of objects of a
specific type. Lists are useful when you need to work with a collection of
objects that can grow or shrink in size.

Main top List<T> methods

Add(): Adds an object to the end of the List<T>.


Contains(): Determines whether an element is in the List<T>.
Count: Gets the number of elements actually contained in the List<T>.
Insert(): Inserts an element into the List<T> at the specified index.
Remove(): Removes the first occurrence of a specific object from the List<T>.
ToArray(): Copies the elements of the List<T> to a new array.

Resizable stores elements of fast element


array a specific type access

Occupy more memory than arrays

Tip: Use List<T> when you have a collection of objects whose size can
change dynamically and you need to perform type-safe operations like add,
remove, and search frequently.

3
LinkedList<T>
A LinkedList<T> is a generic collection of objects of a specific type that
can be efficiently inserted or removed at any position in the list.

Main top LinkedList<T> methods

AddFirst(T value): Adds the specified value to the beginning of the LinkedList<T>.
AddLast(T value): Adds the specified value to the end of the LinkedList<T>.
AddBefore(LinkedListNode<T> node, T value): Adds the specified value before
the specified node in the LinkedList<T>.
AddAfter(LinkedListNode<T> node, T value): Adds the specified value after the
specified node in the LinkedList<T>.
GetEnumerator(): Returns an IEnumerator<T> for the LinkedList<T>.

Doubly fast insertion/deletion


linked list of elements

Slower element access due to traversal

Tip: Use LinkedList<T> when you have a collection of objects whose size can
change dynamically and you need to perform frequent add and remove
operations in the middle of the collection.

4
Queue<T>
The Queue<T> class is a collection of objects arranged in a first-in,
first-out (FIFO) order. It is useful when you want to process elements in
a specific order.

Main top Queue<T> methods


Enqueue(T): adds an element to the end of the queue.
Dequeue(): removes and returns the element at the beginning of the queue.
Peek(): returns the element at the beginning of the queue without removing it.
TrimExcess(): reduces the capacity of the queue to match the number of elements.

FIFO (First In, First Out) Fast insertion at the end and
data structure removal from the front

insertion and deletion of elements


Limited Space
from the middle are time consuming

Tip: Use Queue<T> when you have a collection of objects that needs to
follow a FIFO (First-In-First-Out) pattern, and you need to perform
operations like Enqueue and Dequeue frequently.

5
Stack<T>
The Stack<T> class is a collection of objects arranged in a last-in,
first-out (LIFO) order. It is useful when you want to process elements in
the reverse of the order in which they were added.

Main top Stack<T> methods


Push: Adds an item to the top of the stack.
Pop: Removes and returns the item at the top of the stack.
Peek: Returns the item at the top of the stack without removing it.
CopyTo: Copies the stack elements to an array.
GetEnumerator: Returns an enumerator for iterating through the stack elements.

Managing data that follows Fast insertion at the top and


the LIFO technique removal from the top

Stack memory is of
Random accessing is not possible
limited size

Tip: when you have a collection of objects that needs to follow a LIFO
(Last-In-First-Out) pattern, and you need to perform operations like Push
and Pop frequently.

6
HashSet<T>
The HashSet<T> class is a collection of unique objects that do not have
a specific order. It is useful when you want to ensure that the elements
in the collection are unique.

Main top HashSet<T> methods


Add(T item): Adds an item to the HashSet if it does not already exist.
UnionWith(IEnumerable<T> other): Modifies the current HashSet object to contain all elements
that are present in itself, the specified collection, or both.

IntersectWith(IEnumerable<T> other): Modifies the current HashSet object to contain only

elements that are present in both itself and the specified collection.

ExceptWith(IEnumerable<T> other): Modifies the current HashSet object to contain only

elements that are present in itself and not in the specified collection.

Stores unique elements in no Fast lookup, insertion, and


particular order deletion operations

Not allow duplicate


value

Tip: Use HashSet<T> when you have a collection of unique objects and you
need to perform operations like add, remove, and search frequently.

7
SortedSet<T>
A collection that stores unique elements in sorted order. It is
implemented as a tree-based data structure, which provides a fast search
and retrieval of elements.

Main top SortedSet<T> methods


Add(T item): Adds the specified item to the sorted set.
Remove(T item): Removes the specified item from the sorted set.
Max: Gets the maximum item in the sorted set.
Min: Gets the minimum item in the sorted set.
UnionWith(IEnumerable<T> other): Modifies the sorted set so that it contains all
elements that are present in both the sorted set and the specified collection.

Stores unique elements in Fast lookup, insertion, and


sorted order deletion operations

Can only store the same


type of elements

Tip: Use SortedSet<T> when you have a collection of unique objects that
need to be stored in a sorted order, and you need to perform operations like
add, remove, and search frequently.

8
Dictionary<TKey, TValue>

Dictionary<TKey, TValue> - A collection of key-value pairs that provides


fast lookup of values based on keys.

Main top Dictionary<TKey, TValue> methods

Add(TKey, TValue): Adds the specified key-value pair to the dictionary.


ContainsKey(TKey): Determines whether the dictionary contains the specified key.
ContainsValue(TValue): Determines whether the dictionary contains the specified value.
Remove(TKey): Removes the element with the specified key from the dictionary.
TryGetValue(TKey, out TValue): Gets the value associated with the specified key.
Keys: Gets a collection of the keys in the dictionary.
Values: Gets a collection of the values in the dictionary.

Fast lookup and insertion of


Stores key-value pairs
elements

Slower element access due


to hashing collisions

Tip: Use Dictionary<TKey, TValue> when you have a collection of key-value


pairs and you need to perform operations like add, remove, and search
frequently based on the key.

9
SortedDictionary<TKey, TValue>

Similar to Dictionary<TKey, TValue>, but the keys are stored in sorted


order.

Main top SortedDictionary<TKey, TValue> methods

Add(TKey, TValue): This method is used to add a new key-value pair to the SortedDictionary.

Remove(TKey): This method is used to remove a key-value pair from the SortedDictionary based on the

specified key.
ContainsKey(TKey): This method is used to check whether the SortedDictionary contains a specified key or not.
ContainsValue(TValue): This method is used to check whether the SortedDictionary contains a
specified value or not.
Keys: This property returns a collection of all keys in the SortedDictionary.
Values: This property returns a collection of all values in the SortedDictionary.

Stores key-value pairs in Fast lookup, insertion, and


sorted order deletion operations

Value can be null when the type of


the value is of reference type

Tip: Use SortedDictionary<TKey, TValue> when you have a collection of


key-value pairs that need to be stored in a sorted order based on the key,
and you need to perform operations like add, remove, and search
frequently.

10
SortedList<TKey, TValue>

Similar to SortedDictionary<TKey, TValue>, but the collection is


implemented as an array-based data structure.

Main top SortedList<TKey, TValue> methods

Add: This method adds a new key/value pair to the SortedList<TKey, TValue>.
Remove: This method removes the key/value pair with the specified key from the
SortedList<TKey, TValue>.
Keys: This property gets a collection containing the keys in the SortedList<TKey, TValue>.
Values: This property gets a collection containing the values in the SortedList<TKey,
TValue>.

Its elements in a sorted order Fast access to elements


Key-Value Pair
based on the key In binary search

Requires more memory


Fixed capacity Slow insertions
than an unsorted list

Tip: SortedList<TKey, TValue>: Stores key-value pairs in sorted order,


provides fast element access, but slower insertion/deletion of elements due
to shifting.

11
NameValueCollection

A collection of strings that can be accessed by name, Similar to a


dictionary but allows multiple values for a single key.

Main top NameValueCollection methods


Add: Adds a new name-value pair into the collection.
Get: Returns the value associated with the specified key.
GetAllKeys: Returns an array of all the keys in the collection.
GetAllValues: Returns an array of all the values in the collection.
GetValues: Returns an array of values associated with the specified key.
Set: Sets the value associated with the specified key.

Allows multiple values for a


single key

Order of items is not Only supports String


Not thread-safe
guaranteed keys and values

Tip: Stores key-value pairs of strings, used for storing configuration settings
or HTTP headers.

12
ConcurrentBag<T>
A thread-safe collection that stores elements in an unordered manner. It
provides a thread-safe bag of elements that can be added, removed, and
accessed concurrently from multiple threads without the need for
external synchronization.

Main top ConcurrentBag<T> methods


Add: Adds an item to the bag.
TryTake: Attempts to remove and return an item from the bag. If the bag is empty, it
returns false.
ToList: Returns a new List<T> with all the items in the bag.
Count: Returns the number of items in the bag.
IsEmpty: Returns true if the bag is empty, false otherwise.

Using a lock-free
Thread-safe
algorithm

No index-based
Unordered
access

Tip: Thread-safe collection that allows multiple threads to add or remove


elements without blocking.

13
ConcurrentQueue<T>
ConcurrentQueue<T> is a thread-safe data structure that represents a
first-in, first-out (FIFO) collection of elements of type T, where multiple
threads can access the queue simultaneously without interfering with
each other's operations.

Main top ConcurrentQueue<T> methods


Enqueue: Adds an item to the end of the ConcurrentQueue<T>.
TryDequeue: Attempts to remove and return the object at the beginning of the
ConcurrentQueue<T>.
ToArray: Copies the elements of the ConcurrentQueue<T> to a new array.
Contains Determines whether an element is in the ConcurrentQueue<T>.
Peek: Returns object at the beginning of the ConcurrentQueue<T> without removing it.

Optimized for
Thread-safe Scalability
concurrent access

No indexing Limited functionality

Tip: Thread-safe collection that allows multiple threads to add or remove


elements in a FIFO order without blocking.

14
ConcurrentStack<T>
ConcurrentStack<T> is a thread-safe data structure in C# that
represents a last-in, first-out (LIFO) collection of elements of type T,
where multiple threads can access the stack simultaneously without
interfering with each other's operations.

Main top ConcurrentStack<T> methods

Push: Adds an element to the top of the stack.


TryPop: Attempts to remove and return the element at the top of the stack. If the stack is
empty, it returns false.
TryPeek: Attempts to return the element at the top of the stack without removing it. If the
stack is empty, it returns false.
CopyTo: Copies the elements of the stack to an array, starting at a particular index.

Its elements in a sorted order Optimized for


Scalability
based on the key concurrent access

Limited
No indexing
functionality

Tip: Thread-safe collection that allows multiple threads to add or remove


elements in a LIFO order without blocking.

15
ConcurrentDictionary<TKey, TValue>

ConcurrentDictionary<TKey, TValue> is a thread-safe data structure


that represents a collection of key-value pairs, where multiple threads
can access the dictionary simultaneously without interfering with each
other's operations.

Main top ConcurrentDictionary<TKey, TValue> methods


TryAdd: Adds the specified key/value pair to the dictionary if the key does not already
exist, or updates the existing value if the key already exists.
TryGetValue: Gets the value associated with the specified key, if the key exists in the
dictionary.
GetOrAdd: Gets the value associated with the specified key, or adds a new key/value pair to
the dictionary if the key does not exist.

Rich Optimized for


Thread-safe
functionality concurrent access

Memory usage Complexity Limited ordering

Tip: Thread-safe collection that allows multiple threads to add, update, or


remove elements without blocking.

16
Close();

Keivan Damirchi

You might also like