Fundamental Data Structures and Algorithms in C#
Tags: english, datastructures, algorithms, csharp
Published: 2020-04-17 11:54:50

---
title: Fundamental Data Structures and Algorithms in C#
published: true
description: 
tags: english, datastructures, algorithms, csharp
cover_image: https://res.cloudinary.com/dbvcampra/image/upload/v1588403699/Webp.net-resizeimage_5_beudao.jpg
---
<a href="#stiva" style="text-decoration: underline;">Stack</a>
<a href="#coada" style="text-decoration: underline;">Queue</a>
<a href="#lista" style="text-decoration: underline;">Linked List</a>
<a href="#hashtable" style="text-decoration: underline;">Hashtable</a>
<a href="#cautareBinara" style="text-decoration: underline;">Binary Search</a>
<a href="#arboreBinar" style="text-decoration: underline;">Binary Search Tree</a>
<a href="#grafuri" style="text-decoration: underline;">Graphs</a>
<a href="#sorting" style="text-decoration: underline;">Sorting Algorithms</a><br>
<p>The importance of the algorithms complexity is given by the fact that it tells us if the code is scaling. Most fundamental data structures and algorithms are already implemented in the <b>.NET Framework</b>, it is important to know how these data structures work and what time, memory complexity they have for the basic operations: accessing element, searching element, deleting element, adding element.</p>
<a href="https://3.bp.blogspot.com/-FKfFL6z0zcI/XlfPWDD-SGI/AAAAAAAAHPk/MQ1l_RovxXgTIJCTReag9FzJRA3TILiYACLcBGAsYHQ/s1600/7365ce00a403fa7605fd2058c80ea65599ce67a2.png" imageanchor="1"><img border="0" data-original-height="514" data-original-width="953" src="https://3.bp.blogspot.com/-FKfFL6z0zcI/XlfPWDD-SGI/AAAAAAAAHPk/MQ1l_RovxXgTIJCTReag9FzJRA3TILiYACLcBGAsYHQ/s1600/7365ce00a403fa7605fd2058c80ea65599ce67a2.png" /></a>
To get an idea of ​​what a good complexity means and a less good one we have the following chart:<a href="https://3.bp.blogspot.com/-DnioLTNlg2w/XlfPxIW0RlI/AAAAAAAAHPo/Glbj6UQ7KGA1OumrK_w-1-MArhdtKnuvACLcBGAsYHQ/s1600/8920364de7d83c9b50d5c51a5f385f20b4dd65d4.png" imageanchor="1"><img border="0" data-original-height="592" data-original-width="851" src="https://3.bp.blogspot.com/-DnioLTNlg2w/XlfPxIW0RlI/AAAAAAAAHPo/Glbj6UQ7KGA1OumrK_w-1-MArhdtKnuvACLcBGAsYHQ/s1600/8920364de7d83c9b50d5c51a5f385f20b4dd65d4.png" /></a>
<p>In the <b>.NET Framework</b> we have implemented the following data structures: <b>array</b>, <b>stack</b>, <b>queue</b>, <b>linked list</b> and algorithms: <b>binary search</b>, the rest which we do not find in the <b>.NET Framework</b> can be found in <b>NuGet packages</b> or on <b>GitHub</b>. <b>Array</b/> is one of the most used and well-known data structures and I will not go into detail with the operating principle.</p>
<h2 id="stiva"> Stack</h2>
<p><b>Stack</b> is a data structure implemented in the <b>.NET Framework</b> in two ways, simple stack in <b>System.Collections</b> namespace, and stack as generic data structure in <b>System.Collections.Generic</b> namespace, the principle of stack structure operation is LIFO (last in first out), the last element entered first out.</p>
<a href="https://3.bp.blogspot.com/-ZTPyluNn8oU/XlkES_014qI/AAAAAAAAHRs/fG18AQEHxAwtzXiM7nKbssA3sl3uPVAtQCLcBGAsYHQ/s1600/0_SESFJYWU5a-3XM9m.gif" imageanchor="1" ><img border="0" data-original-height="400" data-original-width="640" src="https://3.bp.blogspot.com/-ZTPyluNn8oU/XlkES_014qI/AAAAAAAAHRs/fG18AQEHxAwtzXiM7nKbssA3sl3uPVAtQCLcBGAsYHQ/s1600/0_SESFJYWU5a-3XM9m.gif" /></a> 
Example of using <b>simple stack</b> from the namespace <b>System.Collections</b>:

```csharp
using System;
using System.Collections;
public class SamplesStack  {

   public static void Main()  {

      // Creates and initializes a new Stack.
      Stack myStack = new Stack();
      myStack.Push("Hello");
      myStack.Push("World");
      myStack.Push("!");

      // Displays the properties and values of the Stack.
      Console.WriteLine( "myStack" );
      Console.WriteLine( "\tCount:    {0}", myStack.Count );
      Console.Write( "\tValues:" );
      PrintValues( myStack );
   }

   public static void PrintValues( IEnumerable myCollection )  {
      foreach ( Object obj in myCollection )
         Console.Write( "    {0}", obj );
      Console.WriteLine();
   }
}


/*
This code produces the following output.
myStack
    Count:    3
    Values:    !    World    Hello
*/
```

Example of using <b>generic stack</b> from the namespace <b>System.Collections.Generic</b>:

```csharp
using System;
using System.Collections.Generic;

class Example
{
    public static void Main()
    {
        Stack<string> numbers = new Stack<string>();
        numbers.Push("one");
        numbers.Push("two");
        numbers.Push("three");
        numbers.Push("four");
        numbers.Push("five");

        // A stack can be enumerated without disturbing its contents.
        foreach( string number in numbers )
        {
            Console.WriteLine(number);
        }

        Console.WriteLine("\nPopping '{0}'", numbers.Pop());
        Console.WriteLine("Peek at next item to destack: {0}",
            numbers.Peek());
        Console.WriteLine("Popping '{0}'", numbers.Pop());

        // Create a copy of the stack, using the ToArray method and the
        // constructor that accepts an IEnumerable<T>.
        Stack<string> stack2 = new Stack<string>(numbers.ToArray());

        Console.WriteLine("\nContents of the first copy:");
        foreach( string number in stack2 )
        {
            Console.WriteLine(number);
        }

        // Create an array twice the size of the stack and copy the
        // elements of the stack, starting at the middle of the
        // array.
        string[] array2 = new string[numbers.Count * 2];
        numbers.CopyTo(array2, numbers.Count);

        // Create a second stack, using the constructor that accepts an
        // IEnumerable(Of T).
        Stack<string> stack3 = new Stack<string>(array2);

        Console.WriteLine("\nContents of the second copy, with duplicates and nulls:");
        foreach( string number in stack3 )
        {
            Console.WriteLine(number);
        }

        Console.WriteLine("\nstack2.Contains(\"four\") = {0}",
            stack2.Contains("four"));

        Console.WriteLine("\nstack2.Clear()");
        stack2.Clear();
        Console.WriteLine("\nstack2.Count = {0}", stack2.Count);
    }
}

/* This code example produces the following output:
five
four
three
two
one
Popping 'five'
Peek at next item to destack: four
Popping 'four'
Contents of the first copy:
one
two
three
Contents of the second copy, with duplicates and nulls:
one
two
three
stack2.Contains("four") = False
stack2.Clear()
stack2.Count = 0
 */
```
<b>Stack applications:</b>
<ul>
<li>undo / redo functionality</li>
<li>word reversal</li>
<li>stack back/forward on browsers</li>
<li>backtracking algorithms</li>
<li>bracket verification</li>
</ul>
<h2 id="coada">
Queue</h2>
<b>Queue</b> is a data structure implemented in the <b>.NET Framework</b> in two ways, the simple queue in <b>System.Collections</b> namespace, and the queue as the generic data structure in <b>System.Collections.Generic</b> namespace, the working principle of queue structures is FIFO (first in first out), the first element entered first out.
<a href="https://1.bp.blogspot.com/-N-v_FiIdQXM/XlkFCQQYtPI/AAAAAAAAHR0/zxkuX6WfQS8Y8Mkoj1nHZDWtMOD3MjsUwCLcBGAsYHQ/s1600/0_E33E-AjyAUTFjVmM.gif" imageanchor="1" ><img border="0" src="https://1.bp.blogspot.com/-N-v_FiIdQXM/XlkFCQQYtPI/AAAAAAAAHR0/zxkuX6WfQS8Y8Mkoj1nHZDWtMOD3MjsUwCLcBGAsYHQ/s1600/0_E33E-AjyAUTFjVmM.gif" data-original-width="640" data-original-height="400" /></a>
Example of using <b>the simple queue</b> from the namespace <b>System.Collections</b>:
```csharp
 using System;
 using System.Collections;
 public class SamplesQueue  {

    public static void Main()  {

       // Creates and initializes a new Queue.
       Queue myQ = new Queue();
       myQ.Enqueue("Hello");
       myQ.Enqueue("World");
       myQ.Enqueue("!");

       // Displays the properties and values of the Queue.
       Console.WriteLine( "myQ" );
       Console.WriteLine( "\tCount:    {0}", myQ.Count );
       Console.Write( "\tValues:" );
       PrintValues( myQ );
    }

    public static void PrintValues( IEnumerable myCollection )  {
       foreach ( Object obj in myCollection )
          Console.Write( "    {0}", obj );
       Console.WriteLine();
    }
 }
 /*
 This code produces the following output.
 myQ
     Count:    3
     Values:    Hello    World    !
*/
```
Example of using <b>the generic queue</b> from the namespace <b>System.Collections.Generic</b>:
```csharp
using System;
using System.Collections.Generic;

class Example
{
    public static void Main()
    {
        Queue<string> numbers = new Queue<string>();
        numbers.Enqueue("one");
        numbers.Enqueue("two");
        numbers.Enqueue("three");
        numbers.Enqueue("four");
        numbers.Enqueue("five");

        // A queue can be enumerated without disturbing its contents.
        foreach( string number in numbers )
        {
            Console.WriteLine(number);
        }

        Console.WriteLine("\nDequeuing '{0}'", numbers.Dequeue());
        Console.WriteLine("Peek at next item to dequeue: {0}",
            numbers.Peek());
        Console.WriteLine("Dequeuing '{0}'", numbers.Dequeue());

        // Create a copy of the queue, using the ToArray method and the
        // constructor that accepts an IEnumerable<T>.
        Queue<string> queueCopy = new Queue<string>(numbers.ToArray());

        Console.WriteLine("\nContents of the first copy:");
        foreach( string number in queueCopy )
        {
            Console.WriteLine(number);
        }

        // Create an array twice the size of the queue and copy the
        // elements of the queue, starting at the middle of the
        // array.
        string[] array2 = new string[numbers.Count * 2];
        numbers.CopyTo(array2, numbers.Count);

        // Create a second queue, using the constructor that accepts an
        // IEnumerable(Of T).
        Queue<string> queueCopy2 = new Queue<string>(array2);

        Console.WriteLine("\nContents of the second copy, with duplicates and nulls:");
        foreach( string number in queueCopy2 )
        {
            Console.WriteLine(number);
        }

        Console.WriteLine("\nqueueCopy.Contains(\"four\") = {0}",
            queueCopy.Contains("four"));

        Console.WriteLine("\nqueueCopy.Clear()");
        queueCopy.Clear();
        Console.WriteLine("\nqueueCopy.Count = {0}", queueCopy.Count);
    }
}

/* This code example produces the following output:
one
two
three
four
five
Dequeuing 'one'
Peek at next item to dequeue: two
Dequeuing 'two'
Contents of the copy:
three
four
five
Contents of the second copy, with duplicates and nulls:
three
four
five
queueCopy.Contains("four") = True
queueCopy.Clear()
queueCopy.Count = 0
 */
```
<b>Real life example of queue:</b>
The system from the point of sale of a restaurant.
<h2 id="lista">
Linked List</h2>
<b>Linked List</b> is a data structure implemented in the <b>.NET Framework</b> as a <b>generic data structure</b> in <b>System.Collections.Generic</b> namespace, the principle of functioning of the linked list structures is that each node in the list has a reference to the next node, except the tail of the list, which has no reference to the next node.
<a href="https://1.bp.blogspot.com/-mycmX6b0ubA/XlkFzTEJdZI/AAAAAAAAHSA/-dlS_xT-Wmoh8qPLWWiNO7Lthu8ByHY0wCLcBGAsYHQ/s1600/linked-list-programming-interview-questions-1.gif" imageanchor="1" ><img border="0" src="https://1.bp.blogspot.com/-mycmX6b0ubA/XlkFzTEJdZI/AAAAAAAAHSA/-dlS_xT-Wmoh8qPLWWiNO7Lthu8ByHY0wCLcBGAsYHQ/s1600/linked-list-programming-interview-questions-1.gif" data-original-width="1125" data-original-height="446" /></a>
An example of search in linked list of the third item starting from the end:
<a href="https://2.bp.blogspot.com/-TFPEI7QYVVQ/XlkGVSEJiZI/AAAAAAAAHSI/M_oTsk9FQeEpkqac8UCZiI_dA5Khr8MPQCLcBGAsYHQ/s1600/linked-list-programming-interview-questions-5.gif" imageanchor="1" ><img border="0" src="https://2.bp.blogspot.com/-TFPEI7QYVVQ/XlkGVSEJiZI/AAAAAAAAHSI/M_oTsk9FQeEpkqac8UCZiI_dA5Khr8MPQCLcBGAsYHQ/s1600/linked-list-programming-interview-questions-5.gif" data-original-width="960" data-original-height="383" /></a>
Example of using <b>the generic linked list</b> from namespace <b>System.Collections.Generic</b>:
```csharp
using System;
using System.Text;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create the link list.
        string[] words =
            { "the", "fox", "jumps", "over", "the", "dog" };
        LinkedList<string> sentence = new LinkedList<string>(words);
        Display(sentence, "The linked list values:");
        Console.WriteLine("sentence.Contains(\"jumps\") = {0}",
            sentence.Contains("jumps"));

        // Add the word 'today' to the beginning of the linked list.
        sentence.AddFirst("today");
        Display(sentence, "Test 1: Add 'today' to beginning of the list:");

        // Move the first node to be the last node.
        LinkedListNode<string> mark1 = sentence.First;
        sentence.RemoveFirst();
        sentence.AddLast(mark1);
        Display(sentence, "Test 2: Move first node to be last node:");

        // Change the last node to 'yesterday'.
        sentence.RemoveLast();
        sentence.AddLast("yesterday");
        Display(sentence, "Test 3: Change the last node to 'yesterday':");

        // Move the last node to be the first node.
        mark1 = sentence.Last;
        sentence.RemoveLast();
        sentence.AddFirst(mark1);
        Display(sentence, "Test 4: Move last node to be first node:");

        // Indicate the last occurence of 'the'.
        sentence.RemoveFirst();
        LinkedListNode<string> current = sentence.FindLast("the");
        IndicateNode(current, "Test 5: Indicate last occurence of 'the':");

        // Add 'lazy' and 'old' after 'the' (the LinkedListNode named current).
        sentence.AddAfter(current, "old");
        sentence.AddAfter(current, "lazy");
        IndicateNode(current, "Test 6: Add 'lazy' and 'old' after 'the':");

        // Indicate 'fox' node.
        current = sentence.Find("fox");
        IndicateNode(current, "Test 7: Indicate the 'fox' node:");

        // Add 'quick' and 'brown' before 'fox':
        sentence.AddBefore(current, "quick");
        sentence.AddBefore(current, "brown");
        IndicateNode(current, "Test 8: Add 'quick' and 'brown' before 'fox':");

        // Keep a reference to the current node, 'fox',
        // and to the previous node in the list. Indicate the 'dog' node.
        mark1 = current;
        LinkedListNode<string> mark2 = current.Previous;
        current = sentence.Find("dog");
        IndicateNode(current, "Test 9: Indicate the 'dog' node:");

        // The AddBefore method throws an InvalidOperationException
        // if you try to add a node that already belongs to a list.
        Console.WriteLine("Test 10: Throw exception by adding node (fox) already in the list:");
        try
        {
            sentence.AddBefore(current, mark1);
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine("Exception message: {0}", ex.Message);
        }
        Console.WriteLine();

        // Remove the node referred to by mark1, and then add it
        // before the node referred to by current.
        // Indicate the node referred to by current.
        sentence.Remove(mark1);
        sentence.AddBefore(current, mark1);
        IndicateNode(current, "Test 11: Move a referenced node (fox) before the current node (dog):");

        // Remove the node referred to by current.
        sentence.Remove(current);
        IndicateNode(current, "Test 12: Remove current node (dog) and attempt to indicate it:");

        // Add the node after the node referred to by mark2.
        sentence.AddAfter(mark2, current);
        IndicateNode(current, "Test 13: Add node removed in test 11 after a referenced node (brown):");

        // The Remove method finds and removes the
        // first node that that has the specified value.
        sentence.Remove("old");
        Display(sentence, "Test 14: Remove node that has the value 'old':");

        // When the linked list is cast to ICollection(Of String),
        // the Add method adds a node to the end of the list.
        sentence.RemoveLast();
        ICollection<string> icoll = sentence;
        icoll.Add("rhinoceros");
        Display(sentence, "Test 15: Remove last node, cast to ICollection, and add 'rhinoceros':");

        Console.WriteLine("Test 16: Copy the list to an array:");
        // Create an array with the same number of
        // elements as the linked list.
        string[] sArray = new string[sentence.Count];
        sentence.CopyTo(sArray, 0);

        foreach (string s in sArray)
        {
            Console.WriteLine(s);
        }

        // Release all the nodes.
        sentence.Clear();

        Console.WriteLine();
        Console.WriteLine("Test 17: Clear linked list. Contains 'jumps' = {0}",
            sentence.Contains("jumps"));

        Console.ReadLine();
    }

    private static void Display(LinkedList<string> words, string test)
    {
        Console.WriteLine(test);
        foreach (string word in words)
        {
            Console.Write(word + " ");
        }
        Console.WriteLine();
        Console.WriteLine();
    }

    private static void IndicateNode(LinkedListNode<string> node, string test)
    {
        Console.WriteLine(test);
        if (node.List == null)
        {
            Console.WriteLine("Node '{0}' is not in the list.\n",
                node.Value);
            return;
        }

        StringBuilder result = new StringBuilder("(" + node.Value + ")");
        LinkedListNode<string> nodeP = node.Previous;

        while (nodeP != null)
        {
            result.Insert(0, nodeP.Value + " ");
            nodeP = nodeP.Previous;
        }

        node = node.Next;
        while (node != null)
        {
            result.Append(" " + node.Value);
            node = node.Next;
        }

        Console.WriteLine(result);
        Console.WriteLine();
    }
}

//This code example produces the following output:
//
//The linked list values:
//the fox jumps over the dog

//Test 1: Add 'today' to beginning of the list:
//today the fox jumps over the dog

//Test 2: Move first node to be last node:
//the fox jumps over the dog today

//Test 3: Change the last node to 'yesterday':
//the fox jumps over the dog yesterday

//Test 4: Move last node to be first node:
//yesterday the fox jumps over the dog

//Test 5: Indicate last occurence of 'the':
//the fox jumps over (the) dog

//Test 6: Add 'lazy' and 'old' after 'the':
//the fox jumps over (the) lazy old dog

//Test 7: Indicate the 'fox' node:
//the (fox) jumps over the lazy old dog

//Test 8: Add 'quick' and 'brown' before 'fox':
//the quick brown (fox) jumps over the lazy old dog

//Test 9: Indicate the 'dog' node:
//the quick brown fox jumps over the lazy old (dog)

//Test 10: Throw exception by adding node (fox) already in the list:
//Exception message: The LinkedList node belongs a LinkedList.

//Test 11: Move a referenced node (fox) before the current node (dog):
//the quick brown jumps over the lazy old fox (dog)

//Test 12: Remove current node (dog) and attempt to indicate it:
//Node 'dog' is not in the list.

//Test 13: Add node removed in test 11 after a referenced node (brown):
//the quick brown (dog) jumps over the lazy old fox

//Test 14: Remove node that has the value 'old':
//the quick brown dog jumps over the lazy fox

//Test 15: Remove last node, cast to ICollection, and add 'rhinoceros':
//the quick brown dog jumps over the lazy rhinoceros

//Test 16: Copy the list to an array:
//the
//quick
//brown
//dog
//jumps
//over
//the
//lazy
//rhinoceros

//Test 17: Clear linked list. Contains 'jumps' = False
//
```
<h2 id="hashtable">Hashtable</h2>
<b>Hashtable</b> is a data structure implemented in the <b>.NET Framework</b> in two ways, simple <b>Hashtable</b> in the namespace <b>System.Collections</b> and as generic data structure <b>Dictionary</b> in <b>System.Collections.Generic</b> namespace, it is recommended to use Dictionary instead of Hashtable, the working principle of Hashtable and Dictionary is that construct a hash that is index into an array usually using polynomials. Searching in a Hashtable and Dictionary has the complexity of time <b>O(1)</b>. 
<a href="https://2.bp.blogspot.com/-Ev3g3OAw7x8/XlkJGYgdg6I/AAAAAAAAHSo/UiWwc1NZPikJAClCrlCUafpcxjVoCDQbgCLcBGAsYHQ/s1600/2671f5ebb8358c5347b9d9e3c65b3d50.gif" imageanchor="1" ><img border="0" src="https://2.bp.blogspot.com/-Ev3g3OAw7x8/XlkJGYgdg6I/AAAAAAAAHSo/UiWwc1NZPikJAClCrlCUafpcxjVoCDQbgCLcBGAsYHQ/s1600/2671f5ebb8358c5347b9d9e3c65b3d50.gif" data-original-width="1024" data-original-height="768" /></a>
Example of using generic <b>Dictionary</b> from <b>System.Collections.Generic namespace</b>:
```csharp
// Create a new dictionary of strings, with string keys.
//
Dictionary<string, string> openWith =
    new Dictionary<string, string>();

// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
    openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("An element with Key = \"txt\" already exists.");
}

// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
Console.WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);

// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);

// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] = "winword.exe";

// The indexer throws an exception if the requested key is
// not in the dictionary.
try
{
    Console.WriteLine("For key = \"tif\", value = {0}.",
        openWith["tif"]);
}
catch (KeyNotFoundException)
{
    Console.WriteLine("Key = \"tif\" is not found.");
}

// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
string value = "";
if (openWith.TryGetValue("tif", out value))
{
    Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console.WriteLine("Key = \"tif\" is not found.");
}

// ContainsKey can be used to test keys before inserting
// them.
if (!openWith.ContainsKey("ht"))
{
    openWith.Add("ht", "hypertrm.exe");
    Console.WriteLine("Value added for key = \"ht\": {0}",
        openWith["ht"]);
}

// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
    Console.WriteLine("Key = {0}, Value = {1}",
        kvp.Key, kvp.Value);
}

// To get the values alone, use the Values property.
Dictionary<string, string>.ValueCollection valueColl =
    openWith.Values;

// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console.WriteLine();
foreach( string s in valueColl )
{
    Console.WriteLine("Value = {0}", s);
}

// To get the keys alone, use the Keys property.
Dictionary<string, string>.KeyCollection keyColl =
    openWith.Keys;

// The elements of the KeyCollection are strongly typed
// with the type that was specified for dictionary keys.
Console.WriteLine();
foreach( string s in keyColl )
{
    Console.WriteLine("Key = {0}", s);
}

// Use the Remove method to remove a key/value pair.
Console.WriteLine("\nRemove(\"doc\")");
openWith.Remove("doc");

if (!openWith.ContainsKey("doc"))
{
    Console.WriteLine("Key \"doc\" is not found.");
}

/* This code example produces the following output:
An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe
Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe
Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe
Value = hypertrm.exe
Key = txt
Key = bmp
Key = dib
Key = rtf
Key = doc
Key = ht
Remove("doc")
Key "doc" is not found.
*/
```
<b>Hashtable applications:</b>
<ul>
<li>is used in fast data lookup - the compiler symbol table</li>
<li>indexing the database</li>
<li>caches</li>
<li>unique data representation</li>
</ul>
<p>Of course, the <b>.NET Framework</b> contains several data structures optimized for certain problems, the purpose of this article is not to present all data structures from <b>.NET Framework</b>, I presented only common data structures from courses of algorithms and data structures.</p>
<h2 id="cautareBinara">
Binary Search</h2>
Search algorithms are another topic in the courses of algorithms and data structures, we can use sequential search with <b>O(n)</b> complexity, or <b>binary search</b> with <b>O(log n)</b> complexity if the elements are sorted.
The idea behind binary search is that we access the middle element and compare with the searched one if it is smaller repeats the recursive process for the first half, otherwise it is searching in the second half, the binary search in the <b>.NET Framework</b> is implemented with <b>Array.BinarySearch</b>.
<a href="https://2.bp.blogspot.com/-8p4tjlqWJUA/Xlfp7ZMmXBI/AAAAAAAAHQw/-hwOCmpL-ForYEKgPejMaVgGRfWeCf3agCLcBGAsYHQ/s1600/Binary-Search.png" imageanchor="1"><img border="0" data-original-height="891" data-original-width="1600" src="https://2.bp.blogspot.com/-8p4tjlqWJUA/Xlfp7ZMmXBI/AAAAAAAAHQw/-hwOCmpL-ForYEKgPejMaVgGRfWeCf3agCLcBGAsYHQ/s1600/Binary-Search.png" /></a>
An example of using <b>binary search</b> using the <b>Array.BinarySearch</b> method in the <b>.NET Framework</b>:
```csharp
ass Program  
{  
    static void Main(string[] args)  
    {  
        // Create an array of 10 elements    
        int[] IntArray = new int[10] { 1, 3, 5, 7, 11, 13, 17, 19, 23, 31 };  
        // Value to search for    
        int target = 17;  
        int pos = Array.BinarySearch(IntArray, target);  
        if (pos >= 0)  
            Console.WriteLine($"Item {IntArray[pos].ToString()} found at position {pos + 1}.");  
        else  
            Console.WriteLine("Item not found");  
        Console.ReadKey();  
    }  
```
<h2 id="arboreBinar">
Binary Search Tree</h2>
A GitHub repository with custom implementations for most data structures: <a href="https://github.com/aalhour/C-Sharp-Algorithms" target="_blank">https://github.com/aalhour/C-Sharp-Algorithms</a>.
I will continue to present a binary search tree. The idea is to have a node root, each node has at most two child nodes, the one on the left is smaller than the root, as well as the left subtree, the right node is larger than the root, so is the right subtree.
Example of binary tree construction:
<a href="https://1.bp.blogspot.com/-pGiDeTRcsLg/XlkHp31PCWI/AAAAAAAAHSU/50wl0AFRcBcVEnOsWCoQzELZZAkhi_B8gCLcBGAsYHQ/s1600/binary-search-tree-insertion-animation.gif" imageanchor="1" ><img border="0" src="https://1.bp.blogspot.com/-pGiDeTRcsLg/XlkHp31PCWI/AAAAAAAAHSU/50wl0AFRcBcVEnOsWCoQzELZZAkhi_B8gCLcBGAsYHQ/s1600/binary-search-tree-insertion-animation.gif" data-original-width="400" data-original-height="255" /></a>
Searching in a binary search tree has the complexity of time <b>O(log n)</b> , example of searching in binary tree:
<a href="https://2.bp.blogspot.com/-yVH0ySkTzSc/XlkH1xlGjpI/AAAAAAAAHSY/AAOHTzDFTNMI06I6zi465ENOftos8CVIgCLcBGAsYHQ/s1600/binary-search-tree-sorted-array-animation.gif" imageanchor="1" ><img border="0" src="https://2.bp.blogspot.com/-yVH0ySkTzSc/XlkH1xlGjpI/AAAAAAAAHSY/AAOHTzDFTNMI06I6zi465ENOftos8CVIgCLcBGAsYHQ/s1600/binary-search-tree-sorted-array-animation.gif" data-original-width="450" data-original-height="378" /></a>

<b>Binary search tree traversal:</b>
<b>Preorder</b>
<ul>
<li>Root through</li>
<li>Go through the left subtree</li>
<li>Go through the right subtree</li>
</li>
</ul>
<b>Inorder</b>
<ul>
<li>Go through the left subtree</li>
<li>Root through</li>
<li>Go through the right subtree</li>
</ul>
<b>Postorder</b>
<ul>
<li>Go through the left subtree</li>
<li>Go through the right subtree</li>
<li>Root through</li>
</ul>
In the <b>.NET Framework</b> , the <b>SortedList</b> data structure uses internally a <b>binary tree</b> to keep the sorted elements.
<h2 id="grafuri">Graphs</h2>
<b>The graphs</b> are data structures characterized by nodes and edges joining the nodes, usually using the notation <b>G = (V, E)</b> where, V represents the set of nodes (vertices, vertices), and E represents the set of edges (edges), in the programming language is represented by adjacency matrices for example a [i, j] = k, this means that between node i and j we have an edge with weight k, and adjacent lists are also used for their representation.
<a href="https://1.bp.blogspot.com/-IpYtBbTx2so/XlgW-8pdUZI/AAAAAAAAHRU/yHxOd7zlDssb8Qle7vVxOLbq67n0Y3qWACLcBGAsYHQ/s1600/undirectedgraph.png" imageanchor="1"><img border="0" data-original-height="212" data-original-width="491" src="https://1.bp.blogspot.com/-IpYtBbTx2so/XlgW-8pdUZI/AAAAAAAAHRU/yHxOd7zlDssb8Qle7vVxOLbq67n0Y3qWACLcBGAsYHQ/s1600/undirectedgraph.png" /></a>  
<b>The graphs</b> and <b>trees</b> can also be crossed in <b>breadth(BREADTH FIRST)</b> with a <b>queue</b>, <b>depth(DEPTH FIRST)</b> with a </b>stack</b>.
<a href="https://4.bp.blogspot.com/-Jmkim2LA2Sc/Xlgeg6oMrtI/AAAAAAAAHRg/vopRL-U9cbMGzrjon4_00ov2Sbi5bYuOwCLcBGAsYHQ/s1600/dfsbfs.gif" imageanchor="1"><img border="0" data-original-height="333" data-original-width="640" src="https://4.bp.blogspot.com/-Jmkim2LA2Sc/Xlgeg6oMrtI/AAAAAAAAHRg/vopRL-U9cbMGzrjon4_00ov2Sbi5bYuOwCLcBGAsYHQ/s1600/dfsbfs.gif" /></a>
<h2 id="sorting">
Sorting Algorithms</h2>
<b>Sorting algorithms</b> are another topic from the courses of algorithms and data structures, a table with their complexities:
<a href="https://2.bp.blogspot.com/-oTc6mX9YO1c/XlfsQNo8WlI/AAAAAAAAHQ8/6oewcGTWPQAZlYWDT_lvalfi1x-JgoUagCLcBGAsYHQ/s1600/80a161cc62e754af348a85e9f3f56f92d80bb279%2B%25281%2529.png" imageanchor="1"><img border="0" data-original-height="477" data-original-width="591" src="https://2.bp.blogspot.com/-oTc6mX9YO1c/XlfsQNo8WlI/AAAAAAAAHQ8/6oewcGTWPQAZlYWDT_lvalfi1x-JgoUagCLcBGAsYHQ/s1600/80a161cc62e754af348a85e9f3f56f92d80bb279%2B%25281%2529.png" /></a>