Empty and Size
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 60번째.
HashSet은 비어 있는지 확인하고 크기를 확인하는 메서드를 제공합니다.
빈 HashSet 생성
HashSet<string> colors = new HashSet<string>();Count를 사용하여 HashSet이 비어 있는지 확인
bool isEmpty = colors.Count == 0;
// isEmpty is trueHashSet에 몇 가지 요소를 추가하세요
colors.Add("Red");
colors.Add("Blue");
colors.Add("Green");HashSet의 크기 가져오기
int size = colors.Count;
// size is 3Any() 메서드를 사용하여 HashSet이 비어 있는지 확인할 수도 있습니다.
bool hasElements = colors.Any();
// hasElements는 세트에 요소가 포함되어 있으므로 true입니다.챌린지
쉬움CountAndCheck이라는 메서드를 생성하세요. 이 메서드는 문자열의 HashSet을 인수로 받습니다. 메서드는 다음을 수행해야 합니다:
- HashSet이 비어 있는지 확인하세요.
- 비어 있으면 "Empty set"을 출력하세요.
- 그렇지 않으면 HashSet의 요소 수인 {count}를 사용하여 "Set contains {count} elements"를 출력하세요.
치트 시트
HashSet이 비어 있는지 Count를 사용하여 확인:
bool isEmpty = colors.Count == 0;HashSet의 크기 가져오기:
int size = colors.Count;HashSet에 요소가 있는지 Any()를 사용하여 확인:
bool hasElements = colors.Any();직접 해보기
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void CountAndCheck(HashSet<string> set)
{
// 여기에 코드를 작성하세요
}
static void Main(string[] args)
{
// 쉼표로 구분된 HashSet 요소들의 입력을 읽습니다
// 입력이 비어 있으면 빈 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);
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리 및 흐름의 모든 레슨
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