Checking if an Element Exists
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 59/66。
Contains(element) メソッドは、HashSet に特定の要素が存在するかどうかを確認します。要素が見つかった場合は true を、それ以外の場合は false を返します。
空の HashSet を作成します:
HashSet<string> fruits = new HashSet<string>();HashSet にいくつかの要素を追加します:
fruits.Add("Apple");
fruits.Add("Banana");要素が存在するかどうかを確認:
bool hasApple = fruits.Contains("Apple"); // Returns true
bool hasOrange = fruits.Contains("Orange"); // Returns false結果を条件文で使用できます:
if (fruits.Contains("Apple"))
{
Console.WriteLine("Apple is in the set");
}チャレンジ
簡単ElementExists という名前のメソッドを作成し、以下の 2 つの引数を受け取るようにしてください:
- 文字列の HashSet (
set) - チェックする文字列 (
element)
このメソッドは、要素がセットに存在するかどうかをチェックし、文字列メッセージを返却してください:
- 要素が存在する場合、"The element 'X' exists in the set" を返却
- 要素が存在しない場合、"The element 'X' does not exist in the set" を返却
'X' はチェックされている実際の要素の値です。
チートシート
Contains(element) メソッドは、HashSet に特定の要素が存在するかどうかを確認します。要素が見つかった場合は true を返し、そうでなければ false を返します。
空の HashSet を作成:
HashSet<string> fruits = new HashSet<string>();HashSet に要素を追加:
fruits.Add("Apple");
fruits.Add("Banana");要素の存在を確認:
bool hasApple = fruits.Contains("Apple"); // Returns true
bool hasOrange = fruits.Contains("Orange"); // Returns false条件分岐文で使用:
if (fruits.Contains("Apple"))
{
Console.WriteLine("Apple is in the set");
}自分で試してみよう
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Program
{
public static string ElementExists(HashSet<string> set, string element)
{
// ここにコードを書いてください
return "";
}
public static void Main()
{
// JSON形式かどうかを確認するために最初の行を読み取る
string firstLine = Console.ReadLine();
string elementToCheck = Console.ReadLine();
HashSet<string> set = new HashSet<string>();
// 入力がJSON配列形式かどうかを確認
if (firstLine != null && firstLine.StartsWith("[") && firstLine.EndsWith("]"))
{
try
{
// 角括弧の間の内容を抽出
string arrayContent = firstLine.Substring(1, firstLine.Length - 2);
// 正規表現を使用してすべての引用符付き文字列をマッチ
MatchCollection matches = Regex.Matches(arrayContent, @"""([^""]*)""");
foreach (Match match in matches)
{
// キャプチャされたグループ(引用符なし)を追加
if (match.Groups.Count > 1)
{
set.Add(match.Groups[1].Value.Trim());
}
}
// 要素がJSON文字列形式かどうかを確認
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
{
// 従来のカンマ区切りの入力を処理
string[] elements = firstLine.Split(',');
foreach (string element in elements)
{
set.Add(element.Trim());
}
}
string result = ElementExists(set, elementToCheck);
Console.WriteLine(result);
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
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