Data Structures
list of datastructures in c#
In C#, there are various data structures available, each serving different purposes and optimizing specific types of data operations. Here's a list of some of the commonly used data structures in C#:
Collections
Arrays:
Array: Fixed-size, indexed collection of elements.
ArrayList: Resizable array (non-generic).
Lists:
List<T>: Generic resizable array.
LinkedList<T>: Doubly linked list.
Queues:
Queue<T>: First-in, first-out (FIFO) collection.
Stacks:
Stack<T>: Last-in, first-out (LIFO) collection.
Dictionaries:
Dictionary<TKey, TValue>: Collection of key-value pairs.
SortedDictionary<TKey, TValue>: Sorted collection of key-value pairs.
ConcurrentDictionary<TKey, TValue>: Thread-safe collection of key-value pairs.
Sets:
HashSet<T>: Unordered collection of unique elements.
SortedSet<T>: Sorted collection of unique elements.
Special Collections
Observable Collections:
ObservableCollection<T>: Collection that provides notifications when items are added, removed, or when the entire list is refreshed.
ReadOnly Collections:
ReadOnlyCollection<T>: Wrapper for a list that prevents modification.
Concurrent Collections:
ConcurrentQueue<T>: Thread-safe FIFO collection.
ConcurrentStack<T>: Thread-safe LIFO collection.
BlockingCollection<T>: Provides blocking and bounding capabilities for any collection that implements IProducerConsumerCollection<T>.
Specialized Data Structures
BitArrays:
BitArray: Collection of bits represented as true or false.
Heaps and Priority Queues:
Implement custom heap structures for priority queues.
Graphs:
Use custom implementations or third-party libraries.
Trees:
Implement binary trees, AVL trees, or use third-party libraries.
SortedList in C# is a data structure that stores key-value pairs in a sorted order based on the keys. It's part of the System.Collections.Generic namespace and combines the features of a dictionary and a sorted list. Here are the main features and benefits of using SortedList:
Key Features of SortedList:
Sorting: The elements are automatically sorted based on the keys.
Index-Based Access: Allows for access by index, similar to a list, as well as by key, similar to a dictionary.
Duplicates: Keys must be unique, but values can be duplicated.
Performance: Operations such as adding, removing, and looking up items are generally fast due to the underlying data structure.
Syntax and Example:
Here’s how you can create and use a SortedList:
Declaration and Initialization:
csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create a new SortedList
SortedList<int, string> sortedList = new SortedList<int, string>();
// Add elements to the SortedList
sortedList.Add(3, "Three");
sortedList.Add(1, "One");
sortedList.Add(2, "Two");
// Display the elements in sorted order
foreach (KeyValuePair<int, string> kvp in sortedList)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
}
}