Menu
Coddy logo textTech

Checking if an Element Exists

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

The Contains(element) method checks if a specific element exists in the HashSet. It returns true if the element is found, and false otherwise.

Create an empty HashSet:

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

Add some elements to the HashSet:

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

Check if an element exists:

bool hasApple = fruits.Contains("Apple");  // Returns true
bool hasOrange = fruits.Contains("Orange"); // Returns false

You can use the result in conditional statements:

if (fruits.Contains("Apple"))
{
    Console.WriteLine("Apple is in the set");
}
challenge icon

Challenge

Easy

Create a method named ElementExists that takes two arguments:

  • A HashSet of strings (set)
  • A string (element) to check

The method should check if the element exists in the set and return a string message:

  • If the element exists, return "The element 'X' exists in the set"
  • If the element doesn't exist, return "The element 'X' does not exist in the set"

Where 'X' is the actual element value being checked.

Cheat sheet

The Contains(element) method checks if a specific element exists in the HashSet. It returns true if the element is found, and false otherwise.

Create an empty HashSet:

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

Add elements to the HashSet:

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

Check if an element exists:

bool hasApple = fruits.Contains("Apple");  // Returns true
bool hasOrange = fruits.Contains("Orange"); // Returns false

Use in conditional statements:

if (fruits.Contains("Apple"))
{
    Console.WriteLine("Apple is in the set");
}

Try it yourself

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

public class Program
{
    public static string ElementExists(HashSet<string> set, string element)
    {
        // Write your code here
        return "";
    }
    
    public static void Main()
    {
        // Read first line to check if it's JSON format
        string firstLine = Console.ReadLine();
        string elementToCheck = Console.ReadLine();
        HashSet<string> set = new HashSet<string>();
        
        // 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());
                    }
                }
                
                // Check if element is in JSON string format
                Match elementMatch = Regex.Match(elementToCheck, @"""([^""]*)""");
                if (elementMatch.Success && elementMatch.Groups.Count > 1)
                {
                    elementToCheck = elementMatch.Groups[1].Value;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing JSON input: {ex.Message}");
                return;
            }
        }
        else
        {
            // Process traditional comma-separated input
            string[] elements = firstLine.Split(',');
            foreach (string element in elements)
            {
                set.Add(element.Trim());
            }
        }
        
        string result = ElementExists(set, elementToCheck);
        Console.WriteLine(result);
    }
}
quiz iconTest yourself

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

All lessons in Logic & Flow