要素の追加
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部。レッスン 57/66。
Add(element) メソッドは、要素がすでに存在しない場合にその要素を HashSet に追加します。
空の HashSet を作成:
HashSet<string> fruits = new HashSet<string>();セットに「Apple」を追加:
fruits.Add("Apple");上記のコードを実行した後、セット fruits には次のものが含まれています:
{ "Apple" }同じ要素を再度追加しようとしても、2回目は追加されません:
fruits.Add("Apple"); // Returns false, element already existsHashSet は変更されません:
{ "Apple" }チャレンジ
簡単AddElement という名前のメソッドを作成してください。このメソッドは 2 つの引数を受け取ります:
- 文字列の HashSet (
set) - 追加する文字列 (
element)
このメソッドは、指定された要素をセットに追加し、更新されたセットを各要素をカンマとスペースで区切って出力します。要素は中括弧で囲んでください。
例: { Apple, Banana, Cherry }
自分で試してみよう
using System;
using System.Collections.Generic;
class Program
{
public static void AddElement(HashSet<string> set, string element)
{
// ここにコードを書いてください
}
public static void Main()
{
string[] initialElements = Console.ReadLine().Split(',');
string elementToAdd = Console.ReadLine();
HashSet<string> set = new HashSet<string>();
foreach (string item in initialElements)
{
if (!string.IsNullOrWhiteSpace(item))
{
set.Add(item.Trim());
}
}
AddElement(set, elementToAdd);
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
自分で練習してみよう: C#オンラインコンパイラ