Menu
Coddy logo textTech

Iteración sobre conjuntos

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

Iterar sobre un HashSet te permite acceder a cada elemento del conjunto. En C#, puedes usar varios métodos para iterar a través de un HashSet.

Usando un bucle foreach:

// Crear un HashSet
HashSet<string> colors = new HashSet<string>();

// Agregar elementos al HashSet
colors.Add("Red");
colors.Add("Green");
colors.Add("Blue");

// Iterar a través del HashSet
foreach (string color in colors)
{
    Console.WriteLine(color);
}

Recuerda que HashSet no mantiene el orden de inserción, por lo que es posible que los elementos no se recorran en el mismo orden en que se añadieron.

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 reciba un HashSet de enteros como entrada. El método debe iterar por el conjunto e imprimir cada elemento en una línea nueva.

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

5 2 8

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

Practica por tu cuenta: Compilador de C# online