計算機科学のブログ

enums and collections - Organizing your data - List, Methods, Add, Contains, RemoveAt, IndexOf

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 8(enums and collections - Organizing your data)、p.423(Code Magnets)の解答を求めてみる。

コード

Program.cs

using System;
using System.Collections.Generic;

namespace MyFirstConsoleApp
{
    class Program
    {
        static void PppPppL(List<string> a)
        {
            foreach (var element in a)
            {
                Console.WriteLine(element);
            }
        }
        static void Main(string[] args)
        {
            string zilch = "zero";
            string first = "one";
            string second = "two";
            string third = "three";
            string fourth = "4.2";
            string twopointtwo = "2.2";
            List<string> a = new List<string>();

            a.Add(zilch);
            a.Add(first);
            a.Add(second);
            a.Add(third);

            if (a.Contains("three"))
            {
                a.Add("four");
            }
            a.RemoveAt(2);
            if (a.IndexOf("four") != 4)
            {
                a.Add(fourth);
            }
            if (a.Contains("two"))
            {
                a.Add(twopointtwo);
            }
            PppPppL(a);
        }
    }
}

入出力結果(Terminal, Zsh)

zero
one
three
four
4.2