{"id":646,"date":"2023-09-26T23:09:50","date_gmt":"2023-09-27T05:09:50","guid":{"rendered":"https:\/\/kop.lat\/blog\/?p=646"},"modified":"2023-09-26T23:34:52","modified_gmt":"2023-09-27T05:34:52","slug":"data-structures-in-c","status":"publish","type":"post","link":"https:\/\/kop.lat\/blog\/data-structures-in-c\/","title":{"rendered":"Data Structures in C#"},"content":{"rendered":"\n<p>Here are ten commonly used data structures in C#:<\/p>\n\n\n\n<ol>\n<li><strong>Arrays<\/strong>:<br>Arrays are the simplest form of data structures in C#. They are a fixed-size collection of elements of the same data type, accessed by their index. Arrays provide fast random access but have a fixed size.<\/li>\n\n\n\n<li><strong>Lists<\/strong>:<br>Lists are dynamic arrays in C# that automatically resize as needed. They are part of the <code>System.Collections.Generic<\/code> namespace and provide easy insertion and removal of elements.<\/li>\n\n\n\n<li><strong>Dictionaries<\/strong>:<br>Dictionaries, represented by <code>Dictionary&lt;TKey, TValue&gt;<\/code>, are key-value pairs that provide fast lookup based on keys. They are useful for storing and retrieving data based on unique identifiers.<\/li>\n\n\n\n<li><strong>Stacks<\/strong>:<br>Stacks are a Last-In, First-Out (LIFO) data structure. You can use the <code>Stack&lt;T&gt;<\/code> class to push and pop elements from the top of the stack.<\/li>\n\n\n\n<li><strong>Queues<\/strong>:<br>Queues are a First-In, First-Out (FIFO) data structure. You can use the <code>Queue&lt;T&gt;<\/code> class to enqueue elements to the back and dequeue from the front.<\/li>\n\n\n\n<li><strong>LinkedLists<\/strong>:<br>Linked lists are collections of nodes, where each node contains a value and a reference to the next node. They provide efficient insertion and removal of elements in the middle of the list.<\/li>\n\n\n\n<li><strong>HashSet<\/strong>:<br>A <code>HashSet&lt;T&gt;<\/code> is an unordered collection of unique elements. It&#8217;s useful for quickly checking for the existence of an element and ensuring uniqueness.<\/li>\n\n\n\n<li><strong>SortedSet<\/strong>:<br>A <code>SortedSet&lt;T&gt;<\/code> is similar to a <code>HashSet<\/code>, but it maintains elements in sorted order. It provides efficient operations for finding minimum and maximum values.<\/li>\n\n\n\n<li><strong>Stack-based Collections<\/strong>:<br>C# provides several stack-based collections like <code>Stack&lt;T&gt;<\/code>, <code>Queue&lt;T&gt;<\/code>, and <code>ConcurrentStack&lt;T&gt;<\/code> for thread-safe stack operations.<\/li>\n\n\n\n<li><strong>Tree Structures<\/strong>:<br>C# does not provide built-in tree structures, but you can implement binary trees, AVL trees, or other tree-based structures using custom classes.<\/li>\n<\/ol>\n\n\n\n<p>These are some of the commonly used data structures in C#. <\/p>\n\n\n\n<p>Depending on the application and requirements, may also be encountered other specialized data structures such as heaps, graphs, and hash tables that are not part of the standard C# libraries but can be implemented or found in third-party libraries. <\/p>\n\n\n\n<p>The choice of data structure depends on the specific use case and the performance characteristics needed for the application.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Heaps<\/h2>\n\n\n\n<p>In C#, heaps are often implemented as priority queues using data structures like binary heaps. Priority queues are useful for managing elements with priorities, and they ensure that the element with the highest (or lowest) priority is always at the top of the queue. Here&#8217;s an example of how to use a binary heap (min-heap) in C#:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using System;\nusing System.Collections.Generic;\n\nclass MinHeap&lt;T&gt; where T : IComparable&lt;T&gt;\n{\n    private List&lt;T&gt; heap = new List&lt;T&gt;();\n\n    public int Count =&gt; heap.Count;\n\n    public void Add(T item)\n    {\n        heap.Add(item);\n        int currentIndex = Count - 1;\n        while (currentIndex &gt; 0)\n        {\n            int parentIndex = (currentIndex - 1) \/ 2;\n            if (heap&#91;currentIndex].CompareTo(heap&#91;parentIndex]) &gt;= 0)\n                break;\n\n            \/\/ Swap the current element with its parent\n            T temp = heap&#91;currentIndex];\n            heap&#91;currentIndex] = heap&#91;parentIndex];\n            heap&#91;parentIndex] = temp;\n\n            currentIndex = parentIndex;\n        }\n    }\n\n    public T ExtractMin()\n    {\n        if (Count == 0)\n            throw new InvalidOperationException(\"Heap is empty.\");\n\n        T min = heap&#91;0];\n        int lastIndex = Count - 1;\n        heap&#91;0] = heap&#91;lastIndex];\n        heap.RemoveAt(lastIndex);\n        lastIndex--;\n\n        int currentIndex = 0;\n        while (true)\n        {\n            int leftChildIndex = 2 * currentIndex + 1;\n            int rightChildIndex = 2 * currentIndex + 2;\n            int smallestChildIndex = -1;\n\n            if (leftChildIndex &lt;= lastIndex)\n                smallestChildIndex = leftChildIndex;\n\n            if (rightChildIndex &lt;= lastIndex &amp;&amp; heap&#91;rightChildIndex].CompareTo(heap&#91;leftChildIndex]) &lt; 0)\n                smallestChildIndex = rightChildIndex;\n\n            if (smallestChildIndex == -1 || heap&#91;currentIndex].CompareTo(heap&#91;smallestChildIndex]) &lt;= 0)\n                break;\n\n            \/\/ Swap the current element with its smallest child\n            T temp = heap&#91;currentIndex];\n            heap&#91;currentIndex] = heap&#91;smallestChildIndex];\n            heap&#91;smallestChildIndex] = temp;\n\n            currentIndex = smallestChildIndex;\n        }\n\n        return min;\n    }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        MinHeap&lt;int&gt; minHeap = new MinHeap&lt;int&gt;();\n\n        minHeap.Add(4);\n        minHeap.Add(2);\n        minHeap.Add(8);\n        minHeap.Add(1);\n        minHeap.Add(9);\n\n        Console.WriteLine(\"Extracted Min: \" + minHeap.ExtractMin()); \/\/ 1\n        Console.WriteLine(\"Extracted Min: \" + minHeap.ExtractMin()); \/\/ 2\n    }\n}<\/code><\/pre>\n\n\n\n<p>In this example, we define a <code>MinHeap&lt;T><\/code> class that represents a min-heap, where <code>T<\/code> is a type that implements <code>IComparable&lt;T><\/code>. The class provides methods to add elements to the heap (<code>Add<\/code>) and extract the minimum element (<code>ExtractMin<\/code>). The <code>MinHeap<\/code> ensures that the minimum element is always at the root of the heap.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Graphs in c# <\/h2>\n\n\n\n<p>Working with graphs in C# often involves creating custom classes to represent the graph and its components. Here&#8217;s an example of how to create a simple directed graph and perform basic operations like adding vertices and edges, as well as traversing the graph using Depth-First Search (DFS):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using System;\nusing System.Collections.Generic;\n\nclass Graph&lt;T&gt;\n{\n    private Dictionary&lt;T, List&lt;T&gt;&gt; adjacencyList;\n\n    public Graph()\n    {\n        adjacencyList = new Dictionary&lt;T, List&lt;T&gt;&gt;();\n    }\n\n    public void AddVertex(T vertex)\n    {\n        if (!adjacencyList.ContainsKey(vertex))\n            adjacencyList&#91;vertex] = new List&lt;T&gt;();\n    }\n\n    public void AddEdge(T from, T to)\n    {\n        if (!adjacencyList.ContainsKey(from))\n            throw new ArgumentException(\"Vertex 'from' does not exist in the graph.\");\n\n        if (!adjacencyList.ContainsKey(to))\n            throw new ArgumentException(\"Vertex 'to' does not exist in the graph.\");\n\n        adjacencyList&#91;from].Add(to);\n    }\n\n    public void DepthFirstSearch(T startVertex)\n    {\n        HashSet&lt;T&gt; visited = new HashSet&lt;T&gt;();\n        DFS(startVertex, visited);\n    }\n\n    private void DFS(T vertex, HashSet&lt;T&gt; visited)\n    {\n        if (!visited.Contains(vertex))\n        {\n            Console.WriteLine(vertex);\n            visited.Add(vertex);\n\n            if (adjacencyList.ContainsKey(vertex))\n            {\n                foreach (T neighbor in adjacencyList&#91;vertex])\n                {\n                    DFS(neighbor, visited);\n                }\n            }\n        }\n    }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        Graph&lt;string&gt; graph = new Graph&lt;string&gt;();\n\n        graph.AddVertex(\"A\");\n        graph.AddVertex(\"B\");\n        graph.AddVertex(\"C\");\n        graph.AddVertex(\"D\");\n\n        graph.AddEdge(\"A\", \"B\");\n        graph.AddEdge(\"A\", \"C\");\n        graph.AddEdge(\"B\", \"D\");\n        graph.AddEdge(\"C\", \"D\");\n\n        Console.WriteLine(\"Depth-First Search (DFS) starting from 'A':\");\n        graph.DepthFirstSearch(\"A\");\n    }\n}<\/code><\/pre>\n\n\n\n<p>In this example:<\/p>\n\n\n\n<ol>\n<li>We create a <code>Graph&lt;T&gt;<\/code> class that uses a dictionary to represent the adjacency list for the graph. Each vertex is a key in the dictionary, and its associated value is a list of neighboring vertices.<\/li>\n\n\n\n<li>The <code>AddVertex<\/code> method allows us to add vertices to the graph, and the <code>AddEdge<\/code> method allows us to add directed edges between vertices.<\/li>\n\n\n\n<li>The <code>DepthFirstSearch<\/code> method implements Depth-First Search (DFS) to traverse the graph starting from a given vertex. It prints the vertices in the order they are visited.<\/li>\n\n\n\n<li>In the <code>Main<\/code> method, we create a graph with vertices &#8220;A,&#8221; &#8220;B,&#8221; &#8220;C,&#8221; and &#8220;D&#8221; and add edges between them. Then, we perform DFS starting from vertex &#8220;A&#8221; to explore the graph.<\/li>\n<\/ol>\n\n\n\n<p>When you run this program, it will perform a DFS traversal starting from vertex &#8220;A&#8221; and print the vertices in the order they are visited:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Depth-First Search (DFS) starting from 'A':\nA\nB\nD\nC<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Hash Tables<\/h2>\n\n\n\n<p>In C#, hash tables are commonly implemented using the <code>Dictionary&lt;TKey, TValue&gt;<\/code> class, which is part of the <code>System.Collections.Generic<\/code> namespace. Here&#8217;s an example of how to use a hash table (dictionary) in C#:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using System;\nusing System.Collections.Generic;\n\nclass Program\n{\n    static void Main()\n    {\n        \/\/ Create a dictionary (hash table) with string keys and int values\n        Dictionary&lt;string, int&gt; scores = new Dictionary&lt;string, int&gt;();\n\n        \/\/ Add key-value pairs to the dictionary\n        scores&#91;\"Alice\"] = 85;\n        scores&#91;\"Bob\"] = 92;\n        scores&#91;\"Charlie\"] = 78;\n        scores&#91;\"David\"] = 95;\n\n        \/\/ Access values using keys\n        Console.WriteLine(\"Alice's score: \" + scores&#91;\"Alice\"]); \/\/ Output: 85\n\n        \/\/ Check if a key exists in the dictionary\n        if (scores.ContainsKey(\"Bob\"))\n        {\n            Console.WriteLine(\"Bob's score: \" + scores&#91;\"Bob\"]); \/\/ Output: 92\n        }\n\n        \/\/ Remove a key-value pair from the dictionary\n        scores.Remove(\"Charlie\");\n\n        \/\/ Iterate through the dictionary\n        foreach (var kvp in scores)\n        {\n            Console.WriteLine($\"Name: {kvp.Key}, Score: {kvp.Value}\");\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p>In this example:<\/p>\n\n\n\n<ol>\n<li>We create a dictionary <code>scores<\/code> with string keys (representing names) and int values (representing scores).<\/li>\n\n\n\n<li>We add key-value pairs to the dictionary using the <code>[]<\/code> indexer notation.<\/li>\n\n\n\n<li>We access values in the dictionary using keys. If a key is not found, an exception is thrown, so you should use <code>ContainsKey<\/code> to check if a key exists before accessing it.<\/li>\n\n\n\n<li>We remove a key-value pair from the dictionary using the <code>Remove<\/code> method.<\/li>\n\n\n\n<li>We iterate through the dictionary using a <code>foreach<\/code> loop, which allows us to access each key-value pair as a <code>KeyValuePair&lt;TKey, TValue&gt;<\/code>.<\/li>\n<\/ol>\n\n\n\n<p>When you run this program, it will produce output similar to the following:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Alice's score: 85\nBob's score: 92\nName: Alice, Score: 85\nName: Bob, Score: 92\nName: David, Score: 95<\/code><\/pre>\n\n\n\n<p>This example demonstrates how to create, populate, access, and manipulate a hash table (dictionary) in C#. Hash tables are widely used for efficient key-value data storage and retrieval.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Here are ten commonly used data structures in C#: These are some of the commonly used data structures in C#. Depending on the application and requirements, may also be encountered other specialized data structures such as heaps, graphs, and hash tables that are not part of the standard C# libraries but can be implemented or [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":226,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[51,97],"tags":[],"_links":{"self":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/646"}],"collection":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/comments?post=646"}],"version-history":[{"count":3,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/646\/revisions"}],"predecessor-version":[{"id":651,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/646\/revisions\/651"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/media\/226"}],"wp:attachment":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/media?parent=646"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/categories?post=646"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/tags?post=646"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}