Removing an Element
Parte de la sección Lógica y Flujo del Journey de C# de Coddy — lección 58 de 66.
El método Remove(element) elimina el elemento especificado del HashSet, si existe. Este método devuelve true si el elemento se eliminó correctamente, y false si el elemento no se encontró en el conjunto.
Crear un HashSet vacío:
HashSet<string> fruits = new HashSet<string>();Agrega algunos elementos al conjunto:
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Cherry");Después de ejecutar el código anterior, el conjunto fruits contiene:
["Apple", "Banana", "Cherry"]Ahora, elimina "Banana" del conjunto:
bool wasRemoved = fruits.Remove("Banana");Después de eliminar, el conjunto contiene:
["Apple", "Cherry"]El valor de wasRemoved será true porque "Banana" fue encontrado y eliminado.
Si intentamos eliminar un elemento que no existe:
bool wasRemoved = fruits.Remove("Orange");El conjunto permanece sin cambios, y wasRemoved será false.
Desafío
FácilCrea un método llamado RemoveElement que tome dos argumentos:
- Un HashSet de cadenas (
set) - Una cadena (
element) para eliminar
El método debe intentar eliminar el elemento dado del conjunto. Si el elemento fue eliminado exitosamente, imprime "Element removed: True", de lo contrario imprime "Element removed: False". Luego, imprime el conjunto actualizado en una nueva línea.
Hoja de referencia
El método Remove(element) elimina el elemento especificado del HashSet y devuelve true si tiene éxito, false si el elemento no se encontró:
HashSet<string> fruits = new HashSet<string>();
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Cherry");
bool wasRemoved = fruits.Remove("Banana"); // devuelve true
bool notFound = fruits.Remove("Orange"); // devuelve falsePruébalo tú mismo
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Program
{
public static void RemoveElement(HashSet<string> set, string element)
{
// Escribe tu código aquí
}
public static void Main()
{
HashSet<string> set = new HashSet<string>();
// Read first line to check if it's JSON format
string firstLine = Console.ReadLine();
string elementToRemove;
// 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);
// Use regex to match all quoted strings
MatchCollection matches = Regex.Matches(arrayContent, @"""([^""]*)""");
foreach (Match match in matches)
{
// Add the captured group (without quotes)
if (match.Groups.Count > 1)
{
set.Add(match.Groups[1].Value.Trim());
}
}
// Read second line for element to remove
string secondLine = Console.ReadLine();
// Check if element is in JSON string format
Match elementMatch = Regex.Match(secondLine, @"""([^""]*)""");
if (elementMatch.Success && elementMatch.Groups.Count > 1)
{
elementToRemove = elementMatch.Groups[1].Value;
}
else
{
elementToRemove = secondLine;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing JSON input: {ex.Message}");
return;
}
}
else
{
// Process traditional input format
string[] elements = firstLine.Split(',');
foreach (string element in elements)
{
set.Add(element.Trim());
}
// Read element to remove in traditional format
elementToRemove = Console.ReadLine();
}
RemoveElement(set, elementToRemove);
}
}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 Handling8Data Analysis System
Data Collection SetupData Entry Logic11HashSet Part 1
What is a HashSet?Adding an ElementRemoving an ElementChecking if an Element ExistsEmpty and SizeRecap - HashSet3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety