Menu
Coddy logo textTech

Iterating Over Sets

Parte de la sección Lógica y Flujo del Journey de C# de Coddy — lección 66 de 66.

Iterar sobre un HashSet le permite acceder a cada elemento en el conjunto. En C#, puede usar varios enfoques para iterar a través de un HashSet.

Usando un bucle foreach:

// 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);
}

Recuerda que HashSet no mantiene el orden de inserción, por lo que los elementos pueden no ser iterados en el mismo orden en que fueron agregados.

También puedes convertir primero a un array o lista:

// Convertir a un array e iterar
string[] colorArray = colors.ToArray();
for (int i = 0; i < colorArray.Length; i++)
{
    Console.WriteLine(colorArray[i]);
}
challenge icon

Desafío

Fácil

Crea un método llamado PrintSetElements que tome un HashSet de enteros como entrada. El método debe iterar a través del conjunto e imprimir cada elemento en una nueva línea.

Por ejemplo, si el conjunto contiene [5, 2, 8], tu método debe imprimir:

5 2 8

Hoja de referencia

Para iterar sobre un HashSet en C#, use un bucle foreach:

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

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

HashSet no mantiene el orden de inserción, por lo que los elementos pueden no iterarse en el mismo orden en que fueron agregados.

También puedes convertir primero a un array:

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

Pruébalo tú mismo

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

class Program
{
    public static void PrintSetElements(HashSet<int> set)
    {
        // Escribe tu código aquí
    }
    
    static void Main(string[] args)
    {
        HashSet<int> numbers = new HashSet<int>();
        
        // Leer la primera línea para verificar el formato
        string firstLine = Console.ReadLine();
        
        // Verificar si la entrada está en formato de array JSON
        if (firstLine != null && firstLine.StartsWith("[") && firstLine.EndsWith("]"))
        {
            try
            {
                // Extraer el contenido entre corchetes
                string arrayContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Intentar analizar el contenido del array JSON
                string[] values = Regex.Split(arrayContent, @",\s*");
                foreach (string value in values)
                {
                    // Eliminar las comillas si están presentes
                    string cleanValue = value.Trim();
                    if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\""))
                    {
                        cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
                    }
                    
                    // Analizar como entero y agregar al conjunto
                    if (int.TryParse(cleanValue, out int num))
                    {
                        numbers.Add(num);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing JSON input: {ex.Message}");
                return;
            }
        }
        else
        {
            try
            {
                // Formato tradicional - leer conteo luego elementos
                int count = int.Parse(firstLine);
                
                // Leer cada elemento y agregarlo al conjunto
                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 iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Lógica y Flujo