C# - コレクション - List<T>
配列のコレクション版。
< T >の部分に型を指定してnewを行うことで、その型のコレクションとなる。
using System; using System.Collections.Generic; //List class MyMain { public static void Main(string[] args) { List<int> ary = new List<int>(){1,2,3}; List<int> a = new List<int>(){4,5}; //追加 // Listの追加 ary.AddRange(a); PrintArray(ary); //1 2 3 4 5 // 要素の追加 ary.Add(3); PrintArray(ary); //1 2 3 4 5 3 //その値の要素が存在するか Console.WriteLine( ary.Contains(3) ); //True //検索(最初にヒットした要素番号を返す) // 順方向 Console.WriteLine( ary.IndexOf(3) ); //2 // 逆方向 Console.WriteLine( ary.LastIndexOf(3) ); //5 //削除 // 要素番号指定 ary.RemoveAt(2); PrintArray(ary); //1 2 4 5 3 // 値指定、最初にヒットした要素を削除) ary.Remove(2); PrintArray(ary); //1 4 5 3 //挿入(要素番号、値) ary.Insert(3, 2); PrintArray(ary); //1 4 5 2 3 //ソート ary.Sort(); PrintArray(ary); //1 2 3 4 5 //要素の一部の取り出し var ary1 = ary.GetRange(1,3); PrintArray(ary1); //2 3 4 } private static void PrintArray(List<int> a){ foreach(var e in a) { Console.Write("{0} ", e); } Console.WriteLine(); } }