Iterating Over Sets
Coddy'nin C# Journey'sinin Mantık & Akış bölümünün bir parçası — ders 66 / 66.
HashSet üzerinde yineleme yaparak kümedeki her bir öğeye erişebilirsiniz. C#'ta bir HashSet üzerinden yineleme yapmak için çeşitli yaklaşımlar kullanabilirsiniz.
Bir foreach döngüsü kullanarak:
// 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'in ekleme sırasını korumaadığını unutmayın, bu nedenle öğeler eklendikleri sırada aynı şekilde yinelemez.
Ayrıca önce bir diziye veya listeye dönüştürebilirsiniz:
// Convert to array and iterate
string[] colorArray = colors.ToArray();
for (int i = 0; i < colorArray.Length; i++)
{
Console.WriteLine(colorArray[i]);
}
Görev
KolayPrintSetElements adında bir metot oluşturun, bu metot tamsayılar içeren bir HashSet'i girdi olarak alsın. Metot, set içindeki elemanlar üzerinde yineleme yapmalı ve her elemanı yeni bir satıra yazdırmalıdır.
Örneğin, set [5, 2, 8] içeriyorsa, metodunuz şunları yazdırmalıdır:
5 2 8
Kopya kağıdı
C#'ta bir HashSet üzerinde yinelemek için foreach döngüsünü kullanın:
HashSet<string> colors = new HashSet<string>();
colors.Add("Red");
colors.Add("Green");
colors.Add("Blue");
foreach (string color in colors)
{
Console.WriteLine(color);
}
HashSet ekleme sırasını korumaz, bu nedenle öğeler eklendikleri sırada yinelemeyebilir.
Ayrıca önce bir diziye dönüştürebilirsiniz:
string[] colorArray = colors.ToArray();
for (int i = 0; i < colorArray.Length; i++)
{
Console.WriteLine(colorArray[i]);
}
Kendin dene
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
public static void PrintSetElements(HashSet<int> set)
{
// Kodunuzu buraya yazın
}
static void Main(string[] args)
{
HashSet<int> numbers = new HashSet<int>();
// Read first line to check format
string firstLine = Console.ReadLine();
// Check if input is in JSON array format
if (firstLine != null && firstLine.StartsWith("[") && firstLine.EndsWith("]"))
{
try
{
// Extract content between square brackets
string arrayContent = firstLine.Substring(1, firstLine.Length - 2);
// Try to parse the JSON array content
string[] values = Regex.Split(arrayContent, @",\s*");
foreach (string value in values)
{
// Remove any quotes if present
string cleanValue = value.Trim();
if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\""))
{
cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
}
// Parse as integer and add to set
if (int.TryParse(cleanValue, out int num))
{
numbers.Add(num);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing JSON input: {ex.Message}");
return;
}
}
else
{
try
{
// Traditional format - read count then elements
int count = int.Parse(firstLine);
// Read each element and add to the set
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);
}
}Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.
Mantık & Akış bölümündeki tüm dersler
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