Menu
CoddyTech

是否为空及大小

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

HashSet 提供了用于检查是否为空以及确定其大小的方法。

创建一个空的 HashSet

HashSet<string> colors = new HashSet<string>();

使用 Count 检查 HashSet 是否为空

bool isEmpty = colors.Count == 0;
// isEmpty 为 true

向 HashSet 中添加一些元素

colors.Add("Red");
colors.Add("Blue");
colors.Add("Green");

获取 HashSet 的大小

int size = colors.Count;
// size 是 3

你也可以使用 Any() 方法检查 HashSet 是否为空

bool hasElements = colors.Any();
// 由于集合中有元素,hasElements 为 true
challenge icon

挑战

简单

创建一个名为 CountAndCheck 的方法,该方法接收一个字符串 HashSet 作为参数。该方法应:

  1. 检查 HashSet 是否为空。
  2. 如果为空,则打印 "Empty set"。
  3. 否则,打印 "Set contains {count} elements",其中 {count} 是 HashSet 中元素的数量。

亲手试试

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    public static void CountAndCheck(HashSet<string> set)
    {
        // 在这里编写你的代码
    }
    
    static void Main(string[] args)
    {
        // 读取用逗号分隔的 HashSet 元素输入
        // 如果输入为空,就创建一个空的 HashSet
        string input = Console.ReadLine();
        
        HashSet<string> set = new HashSet<string>();
        if (!string.IsNullOrEmpty(input))
        {
            string[] elements = input.Split(',');
            foreach (string element in elements)
            {
                set.Add(element.Trim());
            }
        }
        
        CountAndCheck(set);
    }
}
quiz icon自我测试

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

逻辑与流程中的所有课

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