C# / C# Collections and Generics

Using Dictionaries and HashSets

This tutorial will guide you through the process of using Dictionaries and HashSets in C#. You will learn how to store and retrieve data efficiently using these data structures.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Introduces collections and generics to handle and manipulate data efficiently.

1. Introduction

This tutorial aims to help you understand and implement Dictionaries and HashSets in C#. By the end of this tutorial, you will be able to use these data structures to store and retrieve data in a more efficient manner.

You will learn:

  • What are Dictionaries and HashSets
  • How to create, add and remove items from Dictionaries and HashSets
  • How to access and modify data in Dictionaries and HashSets

Prerequisites:
- Basic knowledge of C#
- Visual Studio or any C# supported IDE installed on your machine

2. Step-by-Step Guide

Dictionaries

A Dictionary in C# is a collection of key-value pairs where each key must be unique. The keys in the dictionary are used to access the values.

To declare a dictionary, use the following syntax:

Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();

Where TKey and TValue are the types of keys and values respectively.

Adding items to the dictionary can be done using the Add method:

dictionary.Add("key1", "value1");

Retrieving a value can be done using the key:

string value = dictionary["key1"]; // value will be "value1"

HashSets

A HashSet in C# is a collection of unique elements. It doesn't maintain any order for storing elements.

To declare a HashSet, use the following syntax:

HashSet<T> hashSet = new HashSet<T>();

Where T is the type of elements in the HashSet.

Adding items to the HashSet can be done using the Add method:

hashSet.Add("value1");

3. Code Examples

Dictionary

// Declare a dictionary
Dictionary<string, int> ages = new Dictionary<string, int>();

// Add items to the dictionary
ages.Add("John", 23);
ages.Add("Emma", 21);

// Access an item in the dictionary
Console.WriteLine(ages["John"]); // Outputs: 23

HashSet

// Declare a HashSet
HashSet<string> names = new HashSet<string>();

// Add items to the HashSet
names.Add("John");
names.Add("Emma");

// Check if an item is in the HashSet
Console.WriteLine(names.Contains("John")); // Outputs: True

4. Summary

In this tutorial, we learned how to use Dictionaries and HashSets in C#. We learned how to add items to these collections, and how to access them.

Next, you could learn about other collections in C#, such as Lists and Stacks. You could also learn how to use LINQ to manipulate these collections.

5. Practice Exercises

  1. Create a dictionary that maps product names to their prices. Add a few products to the dictionary, then print the price of a specific product.

  2. Create a HashSet of student names. Add a few names to the HashSet, then check if a certain name is in the HashSet.

  3. (Advanced) Create a dictionary that maps student names to their grades. Add a few students to the dictionary, then calculate the average grade.

Solutions:

Dictionary<string, double> products = new Dictionary<string, double>();
products.Add("Apple", 0.5);
products.Add("Bread", 1.0);
Console.WriteLine(products["Apple"]); // Outputs: 0.5
HashSet<string> students = new HashSet<string>();
students.Add("John");
students.Add("Emma");
Console.WriteLine(students.Contains("Emma")); // Outputs: True
Dictionary<string, int> grades = new Dictionary<string, int>();
grades.Add("John", 90);
grades.Add("Emma", 85);
double average = grades.Values.Average();
Console.WriteLine(average); // Outputs: 87.5

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help