C# List(リスト)とList(リスト)を結合する

  • 作成日 2020.11.01
  • 更新日 2022.03.04
  • C#
C# List(リスト)とList(リスト)を結合する

C#で、AddRangeを使用して、List(リスト)とList(リスト)を結合するサンプルコードを記述してます。

環境

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

List(リスト)とList(リスト)を結合

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

var lst1 = new List<int> { 1, 2, 3 };
var lst2 = new List<int> { 4, 5 };

lst1.AddRange(lst2);

// 結果
foreach (int i in lst1)
{
	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 lst1 = new List<int> { 1, 2, 3 };
            var lst2 = new List<int> { 4, 5 };

            lst1.AddRange(lst2);
            
            // 結果
            Console.WriteLine(String.Join(" " ,from x in lst1 select x));

        }

    }
}

ラムダ演算子でも同じです。

using System;
using System.Collections.Generic;
using System.Linq;
namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {

            var lst1 = new List<int> { 1, 2, 3 };
            var lst2 = new List<int> { 4, 5 };

            lst1.AddRange(lst2);
            
            // 結果
            Console.WriteLine(String.Join(" " , lst1.Select(x => x)));

        }

    }
}