C# List(リスト)に値を追加する

  • 作成日 2020.12.05
  • 更新日 2022.03.04
  • C#
C# List(リスト)に値を追加する

C#で、Addを使用して、List(リスト)に値を追加するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Microsoft Visual Studio Community 2019 Version 16.7.1

値を追加

Addを使用して、List(リスト)に値を追加します。

ここでは、生成したlistとに「4」と「5」を追加してます。

using System;
using System.Collections.Generic;

namespace testapp
{
    class Program
    {

        static void Main(string[] args)
        {

            var list = new List<int> { 1, 2, 3};

            list.Add(4);
            list.Add(5);

            // 結果
            foreach (int i in list)
            {
                Console.Write("{0} ", i); // 1 2 3 4 5
            }

        }

    }
}

ちなみに、結果の表示は「foreach」ではなく
「Linq」または「ラムダ」を使用して表示することも可能です。

using System;
using System.Collections.Generic;
using System.Linq;

namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {

            var list = new List<int> { 1, 2, 3};

            list.Add(4);
            list.Add(5);

            // 結果 Linq
            Console.WriteLine(String.Join(" ", from i in list select i)); // 1 2 3 4 5
            // 結果 ラムダ演算子
            Console.WriteLine(String.Join(" ", list.Select(i => i))); // 1 2 3 4 5
        }
    }
}