リストの連結
リストを連結させるサンプルです。以下の 2 通りの方法で書いてみました。
- List
.AddRange で要素を追加する - Enumerable.Concat で二つのリストを連結する
using System; using System.Collections.Generic; using System.Linq; class Program { static List<int> Concat1(List<int> xs, List<int> ys) { // 新しいリストを作成して、xs, ys の要素を格納する var ret = new List<int>(xs); ret.AddRange(ys); return ret; } static List<int> Concat2(List<int> xs, List<int> ys) { // Enumerable.Concat でリストを連結する return xs.Concat(ys).ToList(); } static void Main() { var xs = new List<int>() { 1, 2, 3 }; var ys = new List<int>() { 4, 5, 6 }; Console.WriteLine(string.Join(" ", Concat1(xs, ys))); // 1 2 3 4 5 6 Console.WriteLine(string.Join(" ", Concat2(xs, ys))); // 1 2 3 4 5 6 } }
実行結果です。
1 2 3 4 5 6 1 2 3 4 5 6