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 は挿入順序を維持しないことを覚えておいてください。したがって、要素は追加されたのと同じ順序でイテレートされない可能性があります。
また、まず配列またはリストに変換することもできます:
// 配列に変換して反復する
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