Iterating Over Sets
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 66번째.
HashSet을 반복하면 집합의 각 요소에 액세스할 수 있습니다. C#에서는 HashSet을 반복하는 다양한 방법을 사용할 수 있습니다.
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);
}
HashSet은 삽입 순서를 유지하지 않으므로, 요소들은 추가된 순서와 동일하게 반복되지 않을 수 있습니다.
또는 먼저 배열이나 리스트로 변환할 수도 있습니다:
// Convert to array and iterate
string[] colorArray = colors.ToArray();
for (int i = 0; i < colorArray.Length; i++)
{
Console.WriteLine(colorArray[i]);
}
챌린지
쉬움PrintSetElements라는 메서드를 만드세요. 이 메서드는 정수의 HashSet을 입력으로 받아 세트를 반복하면서 각 요소를 새 줄에 출력해야 합니다.
예를 들어, 세트가 [5, 2, 8]을 포함하면 메서드는 다음과 같이 출력해야 합니다:
5 2 8
치트 시트
C#에서 HashSet을 반복하려면 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은 삽입 순서를 유지하지 않으므로 요소는 추가된 순서와 동일하게 반복되지 않을 수 있습니다.
또는 먼저 배열로 변환할 수도 있습니다:
string[] colorArray = colors.ToArray();
for (int i = 0; i < colorArray.Length; i++)
{
Console.WriteLine(colorArray[i]);
}
직접 해보기
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
public static void PrintSetElements(HashSet<int> set)
{
// 여기에 코드를 작성하세요
}
static void Main(string[] args)
{
HashSet<int> numbers = new HashSet<int>();
// 형식을 확인하기 위해 첫 번째 줄 읽기
string firstLine = Console.ReadLine();
// 입력이 JSON 배열 형식인지 확인
if (firstLine != null && firstLine.StartsWith("[") && firstLine.EndsWith("]"))
{
try
{
// 대괄호 사이의 내용 추출
string arrayContent = firstLine.Substring(1, firstLine.Length - 2);
// JSON 배열 내용 파싱 시도
string[] values = Regex.Split(arrayContent, @",\s*");
foreach (string value in values)
{
// 따옴표가 있으면 제거
string cleanValue = value.Trim();
if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\""))
{
cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
}
// 정수로 파싱하여 세트에 추가
if (int.TryParse(cleanValue, out int num))
{
numbers.Add(num);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing JSON input: {ex.Message}");
return;
}
}
else
{
try
{
// 전통 형식 - 개수 읽은 후 요소들 읽기
int count = int.Parse(firstLine);
// 각 요소를 읽어 세트에 추가
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);
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리 및 흐름의 모든 레슨
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