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]);
}
Desafío
FácilCrea 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);
}
}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
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety9HashMap Part 1
What is a HashMap?Declare a HashMapCheck If Key ExistsAccessing ValuesModifying DictionariesRecap - HashMap12HashSet Part 2
Math - Union of HashSetsMath - Intersection of HashSetMath - Set DifferenceMath - Symmetric DifferenceIterating Over Sets