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 falseYou can use the result in conditional statements:
if (fruits.Contains("Apple"))
{
Console.WriteLine("Apple is in the set");
}Challenge
EasyCreate 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 falseUse 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);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling8Data Analysis System
Data Collection SetupData Entry Logic11HashSet Part 1
What is a HashSet?Adding an ElementRemoving an ElementChecking if an Element ExistsEmpty and SizeRecap - HashSet3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety