Menu
Coddy logo textTech

Iterating Over Sets

Part of the Logic & Flow section of Coddy's C# journey — lesson 66 of 66.

Iterating over a HashSet allows you to access each element in the set. In C#, you can use various approaches to iterate through a HashSet.

Using a foreach loop:

// Create a HashSet
HashSet<string> colors = new HashSet<string>();

// Add elements to the HashSet
colors.Add("Red");
colors.Add("Green");
colors.Add("Blue");

// Iterate through the HashSet
foreach (string color in colors)
{
    Console.WriteLine(color);
}

Remember that HashSet doesn't maintain insertion order, so elements may not be iterated in the same order they were added.

You can also convert to an array or list first:

// Convert to array and iterate
string[] colorArray = colors.ToArray();
for (int i = 0; i < colorArray.Length; i++)
{
    Console.WriteLine(colorArray[i]);
}
challenge icon

Challenge

Easy

Create a method named PrintSetElements that takes a HashSet of integers as input. The method should iterate through the set and print each element on a new line.

For example, if the set contains [5, 2, 8], your method should print:

5 2 8

Cheat sheet

To iterate over a HashSet in C#, use a foreach loop:

HashSet<string> colors = new HashSet<string>();
colors.Add("Red");
colors.Add("Green");
colors.Add("Blue");

foreach (string color in colors)
{
    Console.WriteLine(color);
}

HashSet doesn't maintain insertion order, so elements may not be iterated in the same order they were added.

You can also convert to an array first:

string[] colorArray = colors.ToArray();
for (int i = 0; i < colorArray.Length; i++)
{
    Console.WriteLine(colorArray[i]);
}

Try it yourself

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Program
{
    public static void PrintSetElements(HashSet<int> set)
    {
        // Write your code here
    }
    
    static void Main(string[] args)
    {
        HashSet<int> numbers = new HashSet<int>();
        
        // Read first line to check format
        string firstLine = Console.ReadLine();
        
        // Check if input is in JSON array format
        if (firstLine != null && firstLine.StartsWith("[") && firstLine.EndsWith("]"))
        {
            try
            {
                // Extract content between square brackets
                string arrayContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Try to parse the JSON array content
                string[] values = Regex.Split(arrayContent, @",\s*");
                foreach (string value in values)
                {
                    // Remove any quotes if present
                    string cleanValue = value.Trim();
                    if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\""))
                    {
                        cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
                    }
                    
                    // Parse as integer and add to set
                    if (int.TryParse(cleanValue, out int num))
                    {
                        numbers.Add(num);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing JSON input: {ex.Message}");
                return;
            }
        }
        else
        {
            try
            {
                // Traditional format - read count then elements
                int count = int.Parse(firstLine);
                
                // Read each element and add to the set
                for (int i = 0; i < count; i++)
                {
                    int num = int.Parse(Console.ReadLine());
                    numbers.Add(num);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing traditional input: {ex.Message}");
                return;
            }
        }
        
        PrintSetElements(numbers);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow