Menu
Coddy logo textTech

Leer und Größe

Teil des Abschnitts Logik & Ablauf der C#-Journey von Coddy. Lektion 60 von 66.

HashSets bieten Methoden, um zu prüfen, ob sie leer sind, und um ihre Größe zu ermitteln.

Erstelle ein leeres HashSet

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

Prüfe mithilfe von Count, ob das HashSet leer ist

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

Füge einige Elemente zum HashSet hinzu

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

Erhalte die Größe des HashSet

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

Du kannst auch prüfen, ob ein HashSet leer ist, indem du die Any()-Methode verwendest

bool hasElements = colors.Any();
// hasElements ist true, da die Menge Elemente enthält
challenge icon

Aufgabe

Einfach

Erstelle eine Methode namens CountAndCheck, die ein HashSet von Zeichenfolgen als Argument entgegennimmt. Die Methode sollte:

  1. Prüfen, ob das HashSet leer ist.
  2. „Empty set“ ausgeben, wenn es leer ist.
  3. Andernfalls „Set contains {count} elements“ ausgeben, wobei {count} die Anzahl der Elemente im HashSet ist.

Probier es selbst

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

class Program
{
    public static void CountAndCheck(HashSet<string> set)
    {
        // Schreibe deinen Code hier
    }
    
    static void Main(string[] args)
    {
        // Lese Eingabe für HashSet-Elemente, getrennt durch Kommas
        // Wenn die Eingabe leer ist, erstelle einen leeren 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 iconTeste dich selbst

Diese Lektion enthält ein kurzes Quiz. Starte die Lektion, um es zu beantworten und deinen Fortschritt zu speichern.

Alle Lektionen in Logik & Ablauf

Übe selbstständig: Online-C#-Compiler