Book Image

C# Data Structures and Algorithms

By : Marcin Jamro
Book Image

C# Data Structures and Algorithms

By: Marcin Jamro

Overview of this book

Data structures allow organizing data efficiently. They are critical to various problems and their suitable implementation can provide a complete solution that acts like reusable code. In this book, you will learn how to use various data structures while developing in the C# language as well as how to implement some of the most common algorithms used with such data structures. At the beginning, you will get to know arrays, lists, dictionaries, and sets together with real-world examples of your application. Then, you will learn how to create and use stacks and queues. In the following part of the book, the more complex data structures will be introduced, namely trees and graphs, together with some algorithms for searching the shortest path in a graph. We will also discuss how to organize the code in a manageable, consistent, and extendable way. By the end of the book,you will learn how to build components that are easy to understand, debug, and use in different applications.
Table of Contents (14 chapters)

Sorted dictionaries


Both non-generic and generic variants of the hash table-related classes do not keep the order of the elements. For this reason, if you need to present data from the collection sorted by keys, you need to sort them prior to presentation. However, you can use another data structure, the sorted dictionary, to solve this problem and keep keys sorted all the time. Therefore, you can easily get the sorted collection whenever necessary.

The sorted dictionary is implemented as the SortedDictionary generic class, available in the System.Collections.Generic namespace. You can specify types for keys and values while creating a new instance of the SortedDictionary class. Moreover, the class contains similar properties and methods to Dictionary.

First of all, you can use the indexer to get access to a particular element within the collection, as shown in the following line of code:

string value = dictionary["key"]; 

You should ensure that the element exists in the collection. Otherwise...