Menu
Coddy logo textTech

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]);
}
challenge icon

Görev

Kolay

PrintSetElements 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);
    }
}
quiz iconKendini test et

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