Menu
Coddy logo textTech

Removing an Element

Part of the Logic & Flow section of Coddy's C# journey — lesson 58 of 66.

The Remove(element) method removes the specified element from the HashSet, if it exists. This method returns true if the element was successfully removed, and false if the element wasn't found in the set.

Create an empty HashSet:

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

Add some elements to the set:

fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Cherry");

After executing the above code, the set fruits contains:

["Apple", "Banana", "Cherry"]

Now, remove "Banana" from the set:

bool wasRemoved = fruits.Remove("Banana");

After removing, the set contains:

["Apple", "Cherry"]

The value of wasRemoved will be true because "Banana" was found and removed.

If we try to remove an element that doesn't exist:

bool wasRemoved = fruits.Remove("Orange");

The set remains unchanged, and wasRemoved will be false.

challenge icon

Challenge

Easy

Create a method named RemoveElement that takes two arguments:

  1. A HashSet of strings (set)
  2. A string (element) to remove

The method should attempt to remove the given element from the set. If the element was successfully removed, print "Element removed: True", otherwise print "Element removed: False". Then, print the updated set on a new line.

Cheat sheet

The Remove(element) method removes the specified element from the HashSet and returns true if successful, false if the element wasn't found:

HashSet<string> fruits = new HashSet<string>();
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Cherry");

bool wasRemoved = fruits.Remove("Banana"); // returns true
bool notFound = fruits.Remove("Orange");   // returns false

Try it yourself

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class Program
{
    public static void RemoveElement(HashSet<string> set, string element)
    {
        // Write your code here
    }
    
    public static void Main()
    {
        HashSet<string> set = new HashSet<string>();
        
        // Read first line to check if it's JSON format
        string firstLine = Console.ReadLine();
        string elementToRemove;
        
        // 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);
                
                // Use regex to match all quoted strings
                MatchCollection matches = Regex.Matches(arrayContent, @"""([^""]*)""");
                
                foreach (Match match in matches)
                {
                    // Add the captured group (without quotes)
                    if (match.Groups.Count > 1)
                    {
                        set.Add(match.Groups[1].Value.Trim());
                    }
                }
                
                // Read second line for element to remove
                string secondLine = Console.ReadLine();
                
                // Check if element is in JSON string format
                Match elementMatch = Regex.Match(secondLine, @"""([^""]*)""");
                if (elementMatch.Success && elementMatch.Groups.Count > 1)
                {
                    elementToRemove = elementMatch.Groups[1].Value;
                }
                else
                {
                    elementToRemove = secondLine;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing JSON input: {ex.Message}");
                return;
            }
        }
        else
        {
            // Process traditional input format
            string[] elements = firstLine.Split(',');
            foreach (string element in elements)
            {
                set.Add(element.Trim());
            }
            
            // Read element to remove in traditional format
            elementToRemove = Console.ReadLine();
        }
        
        RemoveElement(set, elementToRemove);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow