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)));
}
}
}
-
前の記事
python リスト(配列)を並び替える 2020.11.01
-
次の記事
javascript definePropertyを使用してオブジェクトを書き込み・削除不可にする 2020.11.01
コメントを書く