Empty and Size
Parte de la sección Lógica y Flujo del Journey de C# de Coddy — lección 60 de 66.
Los HashSets proporcionan métodos para comprobar si están vacíos y para determinar su tamaño.
Crear un HashSet vacío
HashSet<string> colors = new HashSet<string>();Verifica si el HashSet está vacío usando Count
bool isEmpty = colors.Count == 0;
// isEmpty is trueAñade algunos elementos al HashSet
colors.Add("Red");
colors.Add("Blue");
colors.Add("Green");Obtener el tamaño del HashSet
int size = colors.Count;
// size is 3También puedes verificar si un HashSet está vacío usando el método Any()
bool hasElements = colors.Any();
// hasElements is true since the set contains elementsDesafío
FácilCrea un método llamado CountAndCheck que tome un HashSet de cadenas como argumento. El método debe:
- Verificar si el HashSet está vacío.
- Imprimir "Empty set" si está vacío.
- De lo contrario, imprimir "Set contains {count} elements" donde {count} es el número de elementos en el HashSet.
Hoja de referencia
Verifica si un HashSet está vacío usando Count:
bool isEmpty = colors.Count == 0;Obtén el tamaño de un HashSet:
int size = colors.Count;Verifica si un HashSet tiene elementos usando Any():
bool hasElements = colors.Any();Pruébalo tú mismo
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void CountAndCheck(HashSet<string> set)
{
// Escribe tu código aquí
}
static void Main(string[] args)
{
// Lee la entrada para elementos de HashSet separados por comas
// Si la entrada está vacía, crea un HashSet vacío
string input = Console.ReadLine();
HashSet<string> set = new HashSet<string>();
if (!string.IsNullOrEmpty(input))
{
string[] elements = input.Split(',');
foreach (string element in elements)
{
set.Add(element.Trim());
}
}
CountAndCheck(set);
}
}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