Empty and Size
Part of the Logic & Flow section of Coddy's C# journey — lesson 60 of 66.
HashSets provide methods to check if they're empty and to determine their size.
Create an empty HashSet
HashSet<string> colors = new HashSet<string>();Check if the HashSet is empty using Count
bool isEmpty = colors.Count == 0;
// isEmpty is trueAdd some elements to the HashSet
colors.Add("Red");
colors.Add("Blue");
colors.Add("Green");Get the size of the HashSet
int size = colors.Count;
// size is 3You can also check if a HashSet is empty using the Any() method
bool hasElements = colors.Any();
// hasElements is true since the set contains elementsChallenge
EasyCreate a method named CountAndCheck that takes a HashSet of strings as an argument. The method should:
- Check if the HashSet is empty.
- Print "Empty set" if it is empty.
- Otherwise, print "Set contains {count} elements" where {count} is the number of elements in the HashSet.
Cheat sheet
Check if a HashSet is empty using Count:
bool isEmpty = colors.Count == 0;Get the size of a HashSet:
int size = colors.Count;Check if a HashSet has elements using Any():
bool hasElements = colors.Any();Try it yourself
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void CountAndCheck(HashSet<string> set)
{
// Write your code here
}
static void Main(string[] args)
{
// Read input for HashSet elements separated by commas
// If the input is empty, create an empty HashSet
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);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
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