Last active
September 29, 2017 07:49
-
-
Save mrgarita/85ac11021f3ca1b66ca7357da4ad8914 to your computer and use it in GitHub Desktop.
C#: リストの要素を削除する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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