Skip to content

Instantly share code, notes, and snippets.

@mrgarita
Last active September 29, 2017 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrgarita/85ac11021f3ca1b66ca7357da4ad8914 to your computer and use it in GitHub Desktop.
Save mrgarita/85ac11021f3ca1b66ca7357da4ad8914 to your computer and use it in GitHub Desktop.
C#: リストの要素を削除する
using System;
using System.Collections.Generic;
namespace リストの要素を削除する
{
class Program
{
static void Main(string[] args)
{
// リストを生成
List<string> items = new List<string>();
// リストに要素を追加
items.Add("トマト"); // items[0] = "トマト"
items.Add("キウイ"); // items[1] = "キウイ"
items.Add("メロン"); // items[2] = "メロン"
// リスト内容を表示
foreach (string item in items)
{
Console.WriteLine(item);
}
// リストの要素を削除
Console.Write("何を消す? ");
string killItem = Console.ReadLine();
// リストの中身を検索して見つかったら削除する(Removeメソッド)
// 戻り値: true 削除した/ false 削除対象の要素がない
bool result = items.Remove(killItem);
if (result == true) Console.WriteLine("消したよ!\n");
else Console.WriteLine("ないよ!\n");
// リスト内容を再度表示
foreach (string item in items)
{
Console.WriteLine(item);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment