Menu
CoddyTech

遍历集合

本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 66 课,共 66 课。

遍历 HashSet 可以让你访问集合中的每个元素。在 C# 中,你可以使用多种方法遍历 HashSet。

使用 foreach 循环:

// 创建一个 HashSet
HashSet<string> colors = new HashSet<string>();

// 向 HashSet 中添加元素
colors.Add("Red");
colors.Add("Green");
colors.Add("Blue");

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

挑战

简单

创建一个名为 PrintSetElements 的方法,它接收一个整数 HashSet 作为输入。该方法应遍历这个集合,并将每个元素打印在新的一行。

例如,如果集合包含 [5, 2, 8],你的方法应打印:

5 2 8

亲手试试

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);
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: C# 在线编译器